1 package org.ssi.util; 2 3 import java.io.InputStream; 4 5 import org.apache.ibatis.session.SqlSession; 6 import org.apache.ibatis.session.SqlSessionFactory; 7 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 8 9 public class MyBatisUtil { 10 /** 11 * 获取SqlSessionFactory 12 * @return SqlSessionFactory 13 */ 14 public static SqlSessionFactory getSqlSessionFactory() { 15 String resource = "conf.xml"; 16 InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource); 17 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); 18 return factory; 19 } 20 21 /** 22 * 获取SqlSession 23 * @return SqlSession 24 */ 25 public static SqlSession getSqlSession() { 26 return getSqlSessionFactory().openSession(); 27 } 28 29 /** 30 * 获取SqlSession 31 * @param isAutoCommit 32 * true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务 33 * false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务 34 * @return SqlSession 35 */ 36 public static SqlSession getSqlSession(boolean isAutoCommit) { 37 return getSqlSessionFactory().openSession(isAutoCommit); 38 } 39 }
有了这个辅助类,获取sqlsession来进行数据的增删改查就不容自己再一遍一遍的写了