MyBatis_自定义工具类简化创建SqlSession过程
主要内容
1、创建自定义工具类: 用于获取SqlSession对象简化使用流程
2、使用自定义工具类,完成sql操作
1. 创建自定义工具类
创建自定义工具类MyBatisUtils.java
package com.bipowernode.utils;
/**
* 自定义工具类
*/
public class MyBatisUtils {
// 当加载当前类,就执行Static静态中的代码且一次
// 定义全局的SqlSessionFactory
private static SqlSessionFactory factory = null;
static{
String config = "mybatis.xml";
try{
InputStream in = Resources.getResourceAsStream(config);
// 使用SqlSessionFactoryBuild创建SqlSessionFactory对象
factory = new SqlSessionFactoryBuilder().build(in);
}catch(IOException e){
e.printStackTrace();
}
}
// 定义一个方法,用户获取SqlSession
public static SqlSession getSqlSession(){
// 如果存在factory,就创建SqlSession对象
SqlSession sqlSession = null;
if (factory !=null){
sqlSession = factory.openSession(); // 非自动提交事务
}
return sqlSession; // 返回sqlSession对象
}
}
2. 使用自定义工具类
package com.bipowernode;
public class MyApp2 {
public static void main(String[] args) throws IOException {
/**
* 访问mybatis读取student配置文件位置
*/
// 使用自定义的工具类获取SqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
String sqlId = "com.bipowernode.dao.StudentDao" + "." + "selectStudents";
List studentList = sqlSession.selectList(sqlId);
studentList.forEach(stu -> System.out.println(stu));
sqlSession.close();
}
}
说明: 使用工具类封装创建SqlSession对象的过程后,获取SqlSession对象就很简单了,只需一行代码。
控制台输出:
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1604125387.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5f9d02cb]
==> Preparing: select id ,name email,age from student order by id;
==> Parameters:
<== Columns: id, email, age
<== Row: 1001, 李四, 20
<== Row: 1002, 张三, 28
<== Row: 1003, 张飞, 20
<== Row: 1004, 刘备, 20
<== Total: 4
Student{id=1001, name='null', email='李四', age=20}
Student{id=1002, name='null', email=' 张三', age=28}
Student{id=1003, name='null', email='张飞', age=20}
Student{id=1004, name='null', email='刘备', age=20}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5f9d02cb]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5f9d02cb]
Returned connection 1604125387 to pool.
说明: 自定义工具类获取SqlSession对象并执行sql操作完成。