前提:已经配置好mybatis的环境。(核心配置文件、mapper映射、实体类、数据库、mapper接口)
工具类:
java
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory = null;
private static String xmlPath = "";//mybatis核心配置文件
private MybatisUtil(){}
static {
try {
InputStream inputStream = Resources.getResourceAsStream(xmlPath);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession openSession(){
return sqlSessionFactory.openSession();
}//手动提交事务,默认。
public static SqlSession openSession(Boolean flag){
return sqlSessionFactory.openSession(flag);
}//自动提交事务
public static void closeSqlSession(SqlSession sqlSession){
if (sqlSession!=null){
sqlSession.close();
}
}//自动提交事务,true时为自动开启事务
public static void dateRoolBack(SqlSession sqlSession){
if (sqlSession!=null){
sqlSession.rollback();
}
}
public static void dateCommit(SqlSession sqlSession){
if (sqlSession!=null){
sqlSession.commit();
}
}
}
使用:
java
SqlSession sqlSession= MybatisUtil.openSession();
Mapper接口 mapper接口对象 = sqlSession.getMapper(Mapper接口.class);
······