首先导包
依赖如下
- <dependencies>
- <dependency>
- <groupId>MySQL</groupId>
- <artifactId>MySQL-connector-java</artifactId>
- <version>8.0.15</version>
- </dependency>
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.5.1</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.11</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
构建 SqlSessionFactory
MyBatis 应用是以 SqlSessionFactory 为中心的, 实例可以通过 SqlSessionFactoryBuilder 获得.
其中 SqlSessionFactory 是工厂接口, 任务用于创建 SqlSession
配置文件将会解析配置 xml 文件在 Configuration 类对象中.
配置 xml 获取数据源, 事务管理器, 映射器
在 resource 文件下新建 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>
- <!-- 定义别名 -->
- <typeAliases>
- <typeAlias type="com.ming.Role" alias="role"/>
- </typeAliases>
- <!-- 定义数据库信息 -->
- <environments default="development">
- <environment id="development">
- <!-- jdbc 事物管理 -->
- <transactionManager type="JDBC"></transactionManager>
- <!-- 数据库链接信息 -->
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://47.94.95.84:32786/mybatis"/>
- <property name="username" value="mybatis"/>
- <property name="password" value="ABCcba20170607"/>
- </dataSource>
- </environment>
- </environments>
- </configuration>
新建类
- package com.ming;
- import org.apache.ibatis.io.Resources;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.apache.ibatis.session.SqlSessionFactoryBuilder;
- import java.io.IOException;
- import java.io.InputStream;
- public class Role {
- public String getSqlSessionFactory(){
- String resource = "mybatis-config.xml";
- try {// 获得输入流
- InputStream inputStream;
- inputStream = Resources.getResourceAsStream(resource);
- // 获得 SqlSessionFactory 工厂
- SqlSessionFactory sqlSessionFactory = null;
- sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- }catch (IOException e){
- e.printStackTrace();
- }
- return null;
- }
- }
最后新建测试类
- package com.ming;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- public class RoleTest {
- private Role role = null;
- @Before
- public void setUp() throws Exception {
- this.role = new Role();
- }
- @After
- public void tearDown() throws Exception {
- }
- @Test
- public void getSqlSessionFactory() {
- role.getSqlSessionFactory();
- }
- }
此时的目录结构
代码方式构建
- public SqlSessionFactory getSqlSessionFactory1(){
- // 创建数据库连接池
- PooledDataSource dataSource = new PooledDataSource();
- dataSource.setDriver("com.mysql.cj.jdbc.Driver");
- dataSource.setUrl("jdbc:mysql://47.94.95.84:32786/mybatis");
- dataSource.setUsername("mybatis");
- dataSource.setPassword("ABCcba20170607");
- // 构建数据库事物
- TransactionFactory transactionFactory = new JdbcTransactionFactory();
- // 创建数据库环境
- Environment environment = new Environment("development", transactionFactory, dataSource);
- // 构建 Configuration 对象
- Configuration configuration = new Configuration(environment);
- // 注册上下文别名
- configuration.getTypeAliasRegistry().registerAlias("role", Role.class);
- // 创建映射器
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
- return sqlSessionFactory;
- }
书写测试用例如下
- package com.ming;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- public class RoleTest {
- private Role role = null;
- @Before
- public void setUp() throws Exception {
- this.role = new Role();
- }
- @After
- public void tearDown() throws Exception {
- }
- @Test
- public void getSqlSessionFactory() {
- role.getSqlSessionFactory();
- }
- @Test
- public void getSqlSessionFactory1() {
- role.getSqlSessionFactory1();
- }
- }
创建 SqlSession
SqlSession 属于门面, 通过 SqlSession 可以获得需要的什么信息
SqlSession sqlSession = null; try{ // 创建一个 sqlsession 会话 sqlSession = sqlSessionFactory.openSession(); sqlSession.commit(); }catch (Exception e){ // 输出错误信息 System.out.println(e.getMessage()); // 进行事物操作, 回滚数据库数据 sqlSession.rollback(); }finally { // 进行资源关闭 if(sqlSession != null){ sqlSession.close(); } }
SqlSession 作用, 获取映射器, 通过命名信息执行 sql 结果
映射器
映射器由 java 和 xml 文件共同组成, 作用
定义参数类型
描述缓存
描述 sql
定义查询结果和 POJO 映射关系
先给出 java 接口
package com.ming; public interface RoleMapper { public Role getRole(Long id); }
根据给定的 id 获取角色对象
给出映射文件, 然后在生成的时候会根据接口实现类, 生成对象.
先编写 POJO
package com.ming; // POJO public class Role { private int id; private String roleName; private String note; public void setId(int id) { this.id = id; } public void setRoleName(String roleName) { this.roleName = roleName; } public void setNote(String note) { this.note = note; } public int getId() { return id; } public String getRoleName() { return roleName; } public String getNote() { return note; } }
在编写映射配置文件
<?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.ming.RoleMapper"> <!-- 定义的接口方法为 getRole 类型参数为 long 返回的结果为 role 即之前定义在 xml 文件中定义的 vo 别名 --> <select id="getRole" parameterType="int" resultType="role"> <!-- 定义 sql 语句 --> SELECT id, role_name as roleName, note FROM t_role WHERE id = #{id} </select> </mapper>
最后编写 mybatis, 添加映射器配置文件
<?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> <!-- 定义别名 --> <typeAliases> <typeAlias type="com.ming.Role" alias="role"/> </typeAliases> <!-- 定义数据库信息 --> <environments default="development"> <environment id="development"> <!-- jdbc 事物管理 --> <transactionManager type="JDBC"></transactionManager> <!-- 数据库链接信息 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://47.94.95.84:32786/mybatis"/> <property name="username" value="mybatis"/> <property name="password" value="ABCcba20170607"/> </dataSource> </environment> </environments> <!-- 定义映射器 --> <mappers> <mapper resource="RoleMapper.xml"></mapper> </mappers> </configuration>
最后再编写执行 sql 的类
package com.ming; import org.apache.ibatis.datasource.pooled.PooledDataSource; import org.apache.ibatis.io.Resources; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import java.io.IOException; import java.io.InputStream; public class MyBatis { public String getSqlSessionFactory(){ String resource = "mybatis-config.xml"; SqlSessionFactory sqlSessionFactory = null; try {// 获得输入流 InputStream inputStream; inputStream = Resources.getResourceAsStream(resource); // 获得 SqlSessionFactory 工厂 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); }catch (IOException e){ e.printStackTrace(); } SqlSession sqlSession = null; try{ // 创建一个 sqlsession 会话 sqlSession = sqlSessionFactory.openSession(); // 获得映射器 // 接口传入映射器中 RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); // 执行方法 Role role = roleMapper.getRole(0); System.out.println(role.getRoleName()); // 刷新语句并提交链接 sqlSession.commit(); }catch (Exception e){ // 输出错误信息 System.out.println(e.getMessage()); // 进行事物操作, 回滚数据库数据 sqlSession.rollback(); }finally { // 进行资源关闭 if(sqlSession != null){ sqlSession.close(); } } return null; } public SqlSessionFactory getSqlSessionFactory1(){ // 创建数据库连接池 PooledDataSource dataSource = new PooledDataSource(); dataSource.setDriver("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://47.94.95.84:32786/mybatis"); dataSource.setUsername("mybatis"); dataSource.setPassword("ABCcba20170607"); // 构建数据库事物 TransactionFactory transactionFactory = new JdbcTransactionFactory(); // 创建数据库环境 Environment environment = new Environment("development", transactionFactory, dataSource); // 构建 Configuration 对象 Configuration configuration = new Configuration(environment); // 注册上下文别名 configuration.getTypeAliasRegistry().registerAlias("role", MyBatis.class); // 创建映射器 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); return sqlSessionFactory; } }
最后编写测试类
package com.ming; import org.junit.After; import org.junit.Before; import org.junit.Test; public class MyBatisTest { private MyBatis myBatis = null; @Before public void setUp() throws Exception { this.myBatis = new MyBatis(); } @After public void tearDown() throws Exception { } @Test public void getSqlSessionFactory() { myBatis.getSqlSessionFactory(); } @Test public void getSqlSessionFactory1() { myBatis.getSqlSessionFactory1(); } }
执行单元测试
结果如下
即完成了 MyBatis 的一次查询
注解
定义接口
package com.ming; import org.apache.ibatis.annotations.Select; public interface Role1 { @Select (value="SELECT id, role_name as roleName, note FROM t_role WHERE id = #{id}") public Role getRole(int id); }
生命周期
SqlSessionFactoryBuilder
其是利用 xml 或者 java 编码构建 SqlSessionFactory 可以构建多个 SessionFactory 作用 构建器
根据构建器获得 sqlSessionFactory
SqlSessionFactory
创建 SqlSession 一个 SqlSession 相当于 JDBC 的 Connection 对象
此为单例管理
每创建一个 SqlSession 就会创建一个数据库连接
SqlSession
此为一个会话, 相当于一个 Connection 连接 线程不安全
生命周期为一个应用的请求和操作, 可以执行多条 sql
来源: https://yq.aliyun.com/articles/697233