SqlSessionFactoryBuilder只需创建一次
使用单例创建SqlSessionFactory
sqlSesison在局部域中使用
原始Dao方法
需要写dao接口以及实现类
//创建dao接口
public interface UserDao {
public User findUserById(int id) throws Exception;
public void insertUser(User user) throws Exception;
public void eleteUser(int id)throws Exception;
}
//创建dao实现接口
public class UserDaoImpl implements UserDao{
//注入sqlSessionFactory
//通过构造方法注入
private SqlSessionFactory sqlSessionFactory;
public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
this.sqlSessionFactory = sqlSessionFactory;
}
public User findUserById(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("test.findUserById",id);
sqlSession.close();
return user;
}
public void insertUser(User user) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.insert("test.insertUser",user);
sqlSession.commit();
sqlSession.close();
}
public void eleteUser(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.delete("test.deleteUser",id);
sqlSession.commit();
sqlSession.close();
}
}
问题
dao接口实现方法存在大量模板方法,将方法提取会大大减轻程序员工作量
调用sqlsession方法时将statement的id硬编码了
调用sqlsession方法时传入变量,由于sqlsession方法使用泛型,即使变量类型传入错误,在编译阶段中也不会报错