在 Java 项目中,可以将 MyBatis 与 H2 数据库进行集成,以下是具体步骤:
在 Maven 项目的 pom.xml 配置文件中添加 MyBatis 和 H2 数据库的依赖。如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hxstrive</groupId> <artifactId>demo_h2</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>2.3.232</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.10</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build> </project>
创建 person 表对应的 Person 实体类,例如:
package com.hxstrive.h2.mybatis; /** * @author hxstrive.com * @since 1.0.0 2024/9/24 14:14 */ public class Person { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
在 resources 目录下创建mybatis-config.xml配置文件,如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="org.h2.Driver"/> <property name="url" value="jdbc:h2:mem:test-db;DB_CLOSE_DELAY=-1"/> <property name="username" value="sa"/> <property name="password" value=""/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/PersonMapper.xml"/> </mappers> </configuration>
创建一个 Mapper 接口,定义行为,如下:
package com.hxstrive.h2.mybatis; import java.util.List; /** * @author hxstrive.com * @since 1.0.0 2024/9/24 14:14 */ public interface PersonMapper { // 获取所有用户信息 List<Person> getAll(); // 根据ID获取用户信息 Person getById(Integer id); // 插入用户信息 void insert(Person user); // 更新用户信息 void update(Person user); // 删除用户信息 void delete(Integer id); }
在 resources 目录下的 mapper 目录中创建一个 PersonMapper.xml 文件,例如:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.h2.mybatis.PersonMapper"> <select id="getAll" resultType="com.hxstrive.h2.mybatis.Person"> SELECT * FROM person; </select> <select id="getById" parameterType="int" resultType="com.hxstrive.h2.mybatis.Person"> SELECT * FROM person WHERE id = #{id}; </select> <insert id="insert" parameterType="com.hxstrive.h2.mybatis.Person"> INSERT INTO person (id, name) VALUES (#{id}, #{name}); </insert> <update id="update" parameterType="com.hxstrive.h2.mybatis.Person"> UPDATE person SET name = #{name} WHERE id = #{id}; </update> <delete id="delete" parameterType="int"> DELETE FROM person WHERE id = #{id}; </delete> </mapper>
创建一个测试类或在服务类中注入数据访问接口来测试与 H2 数据库的交互。例如:
package com.hxstrive.h2.mybatis; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; /** * @author hxstrive.com * @since 1.0.0 2024/9/24 14:16 */ public class MyBatisH2Example { public static void main(String[] args) { String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); // 创建表 sqlSession.getConnection().createStatement() .execute("CREATE TABLE PERSON(id int primary key, name varchar(255))"); PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class); // 插入数据 Person person = new Person(); person.setId(1000); person.setName("Alice"); personMapper.insert(person); // 查询所有用户 for (Person p : personMapper.getAll()) { System.out.println(p); // 更新 p.setName("Alice-update"); personMapper.update(p); // 查询单个用户信息 Person newP = personMapper.getById(p.getId()); System.out.println(newP); // 删除 personMapper.delete(p.getId()); } sqlSession.commit(); sqlSession.close(); } catch (Exception e) { e.printStackTrace(); } } }
运行上面示例,输出如下:
Person{id=1000, name='Alice'} Person{id=1000, name='Alice-update'}