1.SqlSession的使用范围
1.1 SqlSessionFactoryBuilder:用来创建SqlSessionFactory,只需要把SqlSessionfactoryBuilder当成一个工具类来使用
1.2 SqlSessionFactory:通过SqlSessionFactory来创建SqlSession,通过单例模式管理
SqlSesssionFactory(一旦创建不在销毁,一直使用此实例)
将来Mybatis
1.3 SqlSession:面向用户(程序员)的接口,,里面提共了很多方法,selectOne和selectList
2.原始Dao开发方式(程序员需要编写Dao及其Dao实现类)
2.1 思路:编写Dao及其Dao实现类,需要向Dao中注入SqlSessionFactory,在方法体内创建通过SqlSessionFactory创建SqlSession
2.1.1 Dao接口
public interface StudentDao {
//根据ID查询学生信息
public Student findById(int id) throws Exception;
//添加用户信息
public void insertStudent(Student student) throws Exception;
//删除学生信息
public void deleteStudent(int id) throws Exception;
}
2.1.2 Dao实现类
private SqlSessionFactory sqlSessionFactory;
public StudentDaoImpl(SqlSessionFactory sqlSessionFactory){
this.sqlSessionFactory=sqlSessionFactory;
}
@Override
public Student findById(int id) throws Exception {
// TODO Auto-generated method stub
SqlSession sqlSession=sqlSessionFactory.openSession();
Student stu=sqlSession.selectOne("test.findStudentByName",id);
sqlSession.close();
return stu;
}
2.1.3 总结原始Dao开发问题
1.Dao接口实现类中有大量重复的模板方法,设想将重复的模板方法提取出来,大大减轻程序员的工作量
2.在调用SqlSession方法中将statement硬编码
3.调用SqlSession方法传入变量,由于sqlsession方法使用泛型,即使传入参数类型错误在编译阶段也不会报 错,不利于程序员开发
1.1 SqlSessionFactoryBuilder:用来创建SqlSessionFactory,只需要把SqlSessionfactoryBuilder当成一个工具类来使用
1.2 SqlSessionFactory:通过SqlSessionFactory来创建SqlSession,通过单例模式管理
SqlSesssionFactory(一旦创建不在销毁,一直使用此实例)
将来Mybatis
1.3 SqlSession:面向用户(程序员)的接口,,里面提共了很多方法,selectOne和selectList
2.原始Dao开发方式(程序员需要编写Dao及其Dao实现类)
2.1 思路:编写Dao及其Dao实现类,需要向Dao中注入SqlSessionFactory,在方法体内创建通过SqlSessionFactory创建SqlSession
2.1.1 Dao接口
public interface StudentDao {
//根据ID查询学生信息
public Student findById(int id) throws Exception;
//添加用户信息
public void insertStudent(Student student) throws Exception;
//删除学生信息
public void deleteStudent(int id) throws Exception;
}
2.1.2 Dao实现类
private SqlSessionFactory sqlSessionFactory;
public StudentDaoImpl(SqlSessionFactory sqlSessionFactory){
this.sqlSessionFactory=sqlSessionFactory;
}
@Override
public Student findById(int id) throws Exception {
// TODO Auto-generated method stub
SqlSession sqlSession=sqlSessionFactory.openSession();
Student stu=sqlSession.selectOne("test.findStudentByName",id);
sqlSession.close();
return stu;
}
2.1.3 总结原始Dao开发问题
1.Dao接口实现类中有大量重复的模板方法,设想将重复的模板方法提取出来,大大减轻程序员的工作量
2.在调用SqlSession方法中将statement硬编码
3.调用SqlSession方法传入变量,由于sqlsession方法使用泛型,即使传入参数类型错误在编译阶段也不会报 错,不利于程序员开发
本文详细介绍了MyBatis框架中SqlSession的使用方法及其在原始DAO开发方式中的应用。主要内容包括:SqlSessionFactoryBuilder创建SqlSessionFactory的过程,SqlSessionFactory如何管理SqlSession的生命周期,以及程序员如何通过SqlSession接口进行数据库操作。
1162

被折叠的 条评论
为什么被折叠?



