MyBatis获取SqlSession

package com.ykmimi.dao;

import org.apache.ibatis.session.SqlSession;

import com.ykmimi.entity.Student;
import com.ykmimi.utils.MyBatisUtils; public class StudentDaoImpl implements IStudentDao { private SqlSession sqlSession; @Override
public void insertStu(Student student) {
try {
//通过MyBatis工具类获取SqlSession
sqlSession = MyBatisUtils.getSqlSession();
// .相关操作
sqlSession.insert("stu.insertStudent", student);
sqlSession.commit();
} finally {// 异常在getSqlSession方法中被捕获
if (sqlSession != null) {
sqlSession.close();
}
}
} }

上面getSqlSession()基于下面的工具类

package com.ykmimi.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;
/*
* 获取SqlSession
*/
public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; public static SqlSession getSqlSession() {
try {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
if (sqlSessionFactory == null) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}
return sqlSessionFactory.openSession();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
上一篇:C# 隐藏窗口标题栏、隐藏任务栏图标


下一篇:关于UI回调Invoker的实现(一)