简化工厂
未简化版本
例:将数据使用插入语句插入到数据库中。
- 如下所示测试单元代码。
@Test public void test_insert() { try { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); Student s = new Student(1, "tom", "123@briup.com", new Date()); studentMapper.insertStudent(s); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } }
- 测试结果测试成功。
- 分析
代码使用io流将配置文件写入,再new了一个SqlSessionFactory工厂。
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
简化版
将如上所示三句,写成:
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
@Test
public void test_insert_util() {
try {
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student s = new Student(2, "tom", "123@briup.com", new Date());
studentMapper.insertStudent(s);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
- MyBatisSqlSessionFactory代码,直接调用即可。
package com.briup.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisSqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactory() {
if (sqlSessionFactory == null) {
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
}
return sqlSessionFactory;
}
public static SqlSession openSession() {
return openSession(false);
}
public static SqlSession openSession(boolean autoCommit) {
return getSqlSessionFactory().openSession(autoCommit);
}
}
- 测试结果成功。
查看数据库
数据存在,插入成功。