MyBatis开发Dao的方法
生活随笔
收集整理的這篇文章主要介紹了
MyBatis开发Dao的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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开发Dao的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MyBatis和hibernate本质区
- 下一篇: MyBatis mapper代理方式