Spring+SpringMVC+MyBatis深入學習及搭建(二)——MyBatis原始Dao開發和mapper代理開發(轉寄同上)

來源:互聯網
上載者:User

標籤:存在   put   測試   alt   等於   刪除使用者   rda   設定檔資訊   setup   

前面有寫到Spring+SpringMVC+MyBatis深入學習及搭建(一)——MyBatis的基礎知識。MybatisFirst中存在大量重複的代碼。這次簡化下代碼:

原地址:http://www.cnblogs.com/shanheyongmu/p/7121016.html

使用MyBatis開發Dao,通常有兩種方法,即原始Dao開發方法和Mapper介面開發方法。

1.SqlSession使用範圍

1.1 SqlsessionFactoryBuilder

通過SqlSessionFactoryBuilder建立會話工廠SqlSessionFactory,將SqlSessionFactoryBuilder當成一個工具類使用即可,不需要使用單例管理SqlSessionFactoryBuilder。

在需要建立SqlSessionFactory時候,只需要new一次SqlSessionFactoryBuilder即可。

1.2 SqlsessionFactory

通過SqlSessionFactory建立SqlSession,使用單例模式管理SqlSessionFactory(工廠一旦建立,使用一個執行個體)。

將來MyBatis和Spring整合後,使用單例模式管理SqlSessionFactory。

1.3 SqlSession

SqlSession是一個面向使用者(程式員)的介面。

SqlSession提供了很多操作資料庫的方法,如:selectOne(返回單個對象)、selectList(返回單個或多個對象)。

SqlSession是線程不安全的,在SqlSession實作類別中除了有介面中的方法(操作資料庫的方法)還有資料域屬性。

SqlSession最佳應用場合在方法體內,定義成局部變數使用。

2.原始dao開發方法(程式員需要寫dao介面和dao實作類別) 2.1 思路

程式員需要寫dao介面和dao實作類別。

需要向dao的實作類別中注入SqlSessionFactory,在方法體內通過SqlSessionFactory建立SqlSession.

2.2 dao介面
public interface UserDao {    //根據id查詢使用者資訊    public User findUserById(int id) throws Exception;    //添加使用者資訊    public void insertUser(User user) throws Exception;    //刪除使用者資訊    public void deleteUser(int id) throws Exception;}
2.3 dao介面實作類別
public class UserDaoImpl implements UserDao{    //需要向dao實作類別中注入SqlSessionFactory    //這裡通過構造方法注入    private SqlSessionFactory sqlSessionFactory;    public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {        super();        this.sqlSessionFactory = sqlSessionFactory;    }    @Override    public User findUserById(int id) throws Exception {        SqlSession sqlSession=sqlSessionFactory.openSession();        User user=sqlSession.selectOne("test.findUserById", id);        //釋放資源        sqlSession.close();        return user;    }    @Override    public void insertUser(User user) throws Exception {        SqlSession sqlSession=sqlSessionFactory.openSession();        sqlSession.insert("test.insertUser", user);        //提交事務        sqlSession.commit();        //釋放資源        sqlSession.close();    }    @Override    public void deleteUser(int id) throws Exception {        SqlSession sqlSession=sqlSessionFactory.openSession();        sqlSession.delete("test.deleteUser", id);        //提交事務        sqlSession.commit();        //釋放資源        sqlSession.close();    }}
2.4 測試代碼
public class UserDaoImplTest {    private SqlSessionFactory sqlSessionFactory;        @Before    public void setUp() throws IOException{        //建立sqlSessionFactory        //mybatis設定檔        String resource="SqlMapConfig.xml";        //得到設定檔流        InputStream inputStream=Resources.getResourceAsStream(resource);        //建立會話工廠,傳入mybatis的設定檔資訊        sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);    }        @Test    public void findUserByIdTest() throws Exception{        UserDao userDao=new UserDaoImpl(sqlSessionFactory);        User user=userDao.findUserById(1);        System.out.println(user);    }}
2.5 總結原始dao開發問題

(1)dao介面實作類別方法中存在大量模板方法,設想能否將這些代碼提取出來,大大減輕程式員工作量。

(2)調用sqlSession方法時將statement的id寫入程式碼了。

(3)調用sqlSession方法時傳入的變數,由於sqlSession方法使用泛型,即使變數類型傳入錯誤,在編譯階段也不報錯,不利於程式員開發。

3.mapper代理方法(程式員只需要寫mapper介面(相當於dao介面)) 3.1 思路(mapper代理開發規範)

程式員需要編寫mapper.xml對應檔

程式員編寫mapper介面需要遵循一些開發規範,mybatis可以自動產生mapper介面實作類別代理對象。

開發規範:

(1)在mapper.xml中namespace等於mapper介面地址

(2)mapper.java介面中的方法名和mapper.xml中statement的id一致

(3)mapper.java介面中的方法輸入參數類型和mapper.xml中statement的parameterType指定的類型一致。

(4)mapper.java介面中的方法傳回值類型和mapper.xml中statement的resultType指定的類型一致。

總結:

以上方法開發規範主要是對下邊的代碼進行統一產生:

User user = sqlSession.selectOne("test.findUserById", id);sqlSession.insert("test.insertUser", user);......
3.2 mapper.java
package joanna.yan.mybatis.mapper;import java.util.List;import joanna.yan.mybatis.entity.User;/** * 相當於dao介面 * @author Joanna.Yan * */public interface UserMapper {    //根據id查詢使用者資訊    public User findUserById(int id) throws Exception;    //根據名字查詢使用者    public List<User> findUserByName(String name) throws Exception;    //添加使用者資訊    public void insertUser(User user) throws Exception;    //刪除使用者資訊    public void deleteUser(int id) throws Exception;}
3.3 mapper.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace命名空間,作用就是對sql進行分類化的管理,理解為sql隔離    注意:使用mapper代理開發時,namespace有特殊作用,namespace等於mapper介面地址  --><mapper namespace="joanna.yan.mybatis.mapper.UserMapper">    <select id="findUserById" parameterType="java.lang.Integer" resultType="joanna.yan.mybatis.entity.User">        select * from user where id=#{id}    </select>    <select id="findUserByName" parameterType="java.lang.String" resultType="joanna.yan.mybatis.entity.User">        select * from user where username LIKE ‘%${value}%‘    </select></mapper>
3.4 在SqlMapConfig.xml中載入mapper.xml

3.5 測試
public class UserMapperTest {private SqlSessionFactory sqlSessionFactory;        @Before    public void setUp() throws IOException{        //建立sqlSessionFactory        //mybatis設定檔        String resource="SqlMapConfig.xml";        //得到設定檔流        InputStream inputStream=Resources.getResourceAsStream(resource);        //建立會話工廠,傳入mybatis的設定檔資訊        sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);    }        @Test    public void findUserByIdTest() throws Exception{        SqlSession sqlSession=sqlSessionFactory.openSession();        //建立UserMapper對象,mybatis自動產生mapper代理對象        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);        //調用userMapper的方法        User user=userMapper.findUserById(1);        System.out.println(user);    }        @Test    public void findUserByNameTest() throws Exception{        SqlSession sqlSession=sqlSessionFactory.openSession();        //建立UserMapper對象,mybatis自動產生mapper代理對象        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);        //調用userMapper的方法        List<User> list=userMapper.findUserByName("小明");        System.out.println(list);    }}
3.6一些問題總結3.6.1 代理對象內部調用selectOne或selectList

如果mapper方法返回單個pojo對象(非集合對象),代理對象內部通過selectOne查詢資料庫。

如果mapper方法返回集合對象,代理對象內部通過selectList查詢資料庫。

3.6.2 mapper介面方法參數只能有一個是否影響系統開發

mapper介面方法參數只能有一個,系統是否不利於擴充維護。

系統架構中,dao層的代碼是被業務層公用的。

即使mapper介面只有一個參數,可以使用封裝類型的pojo滿足不同的業務方法的需求。

注意:持久層方法的參數可以用封裝類型、Map等等,service方法中建議不要使用封裝類型(不利於業務層的可擴充)。

Spring+SpringMVC+MyBatis深入學習及搭建(二)——MyBatis原始Dao開發和mapper代理開發(轉寄同上)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.