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; } }
将编程看作是一门艺术,而不单单是个技术。 敲打的英文字符是我的黑白琴键, 思维图纸画出的是我编写的五线谱。 当美妙的华章响起,现实通往二进制的大门即将被打开。