MyBatis开发Dao的方法
生活随笔
收集整理的這篇文章主要介紹了
MyBatis开发Dao的方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.SqlSession的使用范圍
1.1 SqlSessionFactoryBuilder:用來創(chuàng)建SqlSessionFactory,只需要把SqlSessionfactoryBuilder當(dāng)成一個(gè)工具類來使用
1.2 SqlSessionFactory:通過SqlSessionFactory來創(chuàng)建SqlSession,通過單例模式管理
SqlSesssionFactory(一旦創(chuàng)建不在銷毀,一直使用此實(shí)例)
? 將來Mybatis
1.3 SqlSession:面向用戶(程序員)的接口,,里面提共了很多方法,selectOne和selectList
2.原始Dao開發(fā)方式(程序員需要編寫Dao及其Dao實(shí)現(xiàn)類)
2.1 思路:編寫Dao及其Dao實(shí)現(xiàn)類,需要向Dao中注入SqlSessionFactory,在方法體內(nèi)創(chuàng)建通過SqlSessionFactory創(chuàng)建SqlSession
2.1.1 Dao接口
public interface StudentDao {
//根據(jù)ID查詢學(xué)生信息
public Student findById(int id) throws Exception;
//添加用戶信息?
public void insertStudent(Student student) throws Exception;
//刪除學(xué)生信息
public void deleteStudent(int id) throws Exception;
}
2.1.2 Dao實(shí)現(xiàn)類
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 總結(jié)原始Dao開發(fā)問題
1.Dao接口實(shí)現(xiàn)類中有大量重復(fù)的模板方法,設(shè)想將重復(fù)的模板方法提取出來,大大減輕程序員的工作量
2.在調(diào)用SqlSession方法中將statement硬編碼
3.調(diào)用SqlSession方法傳入變量,由于sqlsession方法使用泛型,即使傳入?yún)?shù)類型錯(cuò)誤在編譯階段也不會報(bào)?錯(cuò),不利于程序員開發(fā)
1.1 SqlSessionFactoryBuilder:用來創(chuàng)建SqlSessionFactory,只需要把SqlSessionfactoryBuilder當(dāng)成一個(gè)工具類來使用
1.2 SqlSessionFactory:通過SqlSessionFactory來創(chuàng)建SqlSession,通過單例模式管理
SqlSesssionFactory(一旦創(chuàng)建不在銷毀,一直使用此實(shí)例)
? 將來Mybatis
1.3 SqlSession:面向用戶(程序員)的接口,,里面提共了很多方法,selectOne和selectList
2.原始Dao開發(fā)方式(程序員需要編寫Dao及其Dao實(shí)現(xiàn)類)
2.1 思路:編寫Dao及其Dao實(shí)現(xiàn)類,需要向Dao中注入SqlSessionFactory,在方法體內(nèi)創(chuàng)建通過SqlSessionFactory創(chuàng)建SqlSession
2.1.1 Dao接口
public interface StudentDao {
//根據(jù)ID查詢學(xué)生信息
public Student findById(int id) throws Exception;
//添加用戶信息?
public void insertStudent(Student student) throws Exception;
//刪除學(xué)生信息
public void deleteStudent(int id) throws Exception;
}
2.1.2 Dao實(shí)現(xiàn)類
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 總結(jié)原始Dao開發(fā)問題
1.Dao接口實(shí)現(xiàn)類中有大量重復(fù)的模板方法,設(shè)想將重復(fù)的模板方法提取出來,大大減輕程序員的工作量
2.在調(diào)用SqlSession方法中將statement硬編碼
3.調(diào)用SqlSession方法傳入變量,由于sqlsession方法使用泛型,即使傳入?yún)?shù)類型錯(cuò)誤在編譯階段也不會報(bào)?錯(cuò),不利于程序員開發(fā)
總結(jié)
以上是生活随笔為你收集整理的MyBatis开发Dao的方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MyBatis和hibernate本质区
- 下一篇: MyBatis mapper代理方式