MyBatis入門(二)

學(xué)習(xí)內(nèi)容:

使用Mybatis開發(fā)Dao,通常有兩個(gè)方法:

  1. 原生Dao開發(fā)
  2. Mapper接口開發(fā)方法

1. 原生Dao開發(fā)

1.1 創(chuàng)建配置文件 SqlMapConfig.xml
1.2 創(chuàng)建po類
1.3 創(chuàng)建映射文件、加載映射文件
(參考入門一)
1.4 Dao接口

Public interface UserDao {
    public User getUserById(int id) throws Exception;
    public void insertUser(User user) throws Exception;
}
Public class UserDaoImpl implements UserDao {
    
    //注入SqlSessionFactory
    public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
        this.setSqlSessionFactory(sqlSessionFactory);
    }
    
    private SqlSessionFactory sqlSessionFactory;
    @Override
    public User getUserById(int id) throws Exception {
        SqlSession session = sqlSessionFactory.openSession();
        User user = null;
        try {
            //通過sqlsession調(diào)用selectOne方法獲取一條結(jié)果集
            //參數(shù)1:指定定義的statement的id,參數(shù)2:指定向statement中傳遞的參數(shù)
            user = session.selectOne("test.findUserById", 1);
            System.out.println(user);
                        
        } finally{
            session.close();
        }
        return user;
    }
    
    @Override
    Public void insertUser(User user) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.insert("insertUser", user);
            sqlSession.commit();
        } finally{
            session.close();
        }
        
    }
}

1.5 測試

private SqlSessionFactory sqlSessionFactory;
    
    @Before
    public void init() throws Exception {
        SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        sqlSessionFactory = sessionFactoryBuilder.build(inputStream);
    }
    @Test
    public void testGetUserById() {
        UserDao userDao = new UserDaoImpl(sqlSessionFactory);
        User user = userDao.getUserById(22);
        System.out.println(user);
    }
}

2. Mapper接口開發(fā)方法

Mapper接口開發(fā)方法只需要程序員編寫Mapper接口(相當(dāng)于Dao接口),由Mybatis框架根據(jù)接口定義創(chuàng)建接口的動(dòng)態(tài)代理對象,代理對象的方法體同上邊Dao接口實(shí)現(xiàn)類方法。
Mapper接口開發(fā)需要遵循以下規(guī)范:
1、Mapper.xml文件中的namespace與mapper接口的類路徑相同。
2、 Mapper接口方法名和Mapper.xml中定義的每個(gè)statement的id相同
3、Mapper接口方法的輸入?yún)?shù)類型和mapper.xml中定義的每個(gè)sql 的parameterType的類型相同
4、Mapper接口方法的輸出參數(shù)類型和mapper.xml中定義的每個(gè)sql的resultType的類型相同

步驟

1.1 Mapper.xml(映射文件)

定義mapper映射文件UserMapper.xml(內(nèi)容同Users.xml),需要修改namespace的值為 UserMapper接口路徑。將UserMapper.xml放在classpath 下mapper目錄 下。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

//注意修改
<mapper namespace="cn.itcast.mybatis.mapper.UserMapper">
<!-- 根據(jù)id獲取用戶信息 -->
    <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">
        select * from user where id = #{id}
    </select>
<!-- 自定義條件查詢用戶列表 -->
    <select id="findUserByUsername" parameterType="java.lang.String" 
            resultType="cn.itcast.mybatis.po.User">
       select * from user where username like '%${value}%' 
    </select>
<!-- 添加用戶 -->
    <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
        select LAST_INSERT_ID() 
    </selectKey>
      insert into user(username,birthday,sex,address) 
      values(#{username},#{birthday},#{sex},#{address})
    </insert>

</mapper>
1.2Mapper.java(接口文件)
/**
 * 用戶管理mapper
 */
Public interface UserMapper {
    //根據(jù)用戶id查詢用戶信息
    public User findUserById(int id) throws Exception;
    //查詢用戶列表
    public List<User> findUserByUsername(String username) throws Exception;
    //添加用戶信息
    public void insertUser(User user)throws Exception; 
}

接口定義有如下特點(diǎn):
1、Mapper接口方法名和Mapper.xml中定義的statement的id相同
2、Mapper接口方法的輸入?yún)?shù)類型和mapper.xml中定義的statement的parameterType的類型相同
3、Mapper接口方法的輸出參數(shù)類型和mapper.xml中定義的statement的resultType的類型相同

2.3加載UserMapper.xml文件

修改SqlMapConfig.xml文件:

  <!-- 加載映射文件 -->
  <mappers>
    <mapper resource="mapper/UserMapper.xml"/>
  </mappers>
2.4測試
Public class UserMapperTest extends TestCase {

    private SqlSessionFactory sqlSessionFactory;
    
    protected void setUp() throws Exception {
        //mybatis配置文件
        String resource = "sqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //使用SqlSessionFactoryBuilder創(chuàng)建sessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
      Public void testInsertUser() throws Exception {
        //獲取session
        SqlSession session = sqlSessionFactory.openSession();
        //獲取mapper接口的代理對象
        UserMapper userMapper = session.getMapper(UserMapper.class);
        //要添加的數(shù)據(jù)
        User user = new User();
        user.setUsername("張三");
        user.setBirthday(new Date());
        user.setSex("1");
        user.setAddress("北京市");
        //通過mapper接口添加用戶
        userMapper.insertUser(user);
        //提交
        session.commit();
        //關(guān)閉session
        session.close();
    }

原始Dao開發(fā)中存在以下問題:

  • Dao方法體存在重復(fù)代碼:通過SqlSessionFactory創(chuàng)建SqlSession,調(diào)用SqlSession的數(shù)據(jù)庫操作方法
  • 調(diào)用sqlSession的數(shù)據(jù)庫操作方法需要指定statement的id,這里存在硬編碼,不利于開發(fā)維護(hù)。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 由于之前我們已經(jīng)有了hibernate的基礎(chǔ),所以這里很多細(xì)節(jié)就不再提及。 一、基本架構(gòu) 這里從網(wǎng)絡(luò)上找了幾張my...
    yjaal閱讀 1,586評論 0 7
  • 每個(gè)線程都應(yīng)該有它自己的SqlSession實(shí)例。SqlSession的實(shí)例不能共享使用,它是線程不安全的 配置文...
    蕊er閱讀 482評論 0 0
  • 1 引言# 本文主要講解JDBC怎么演變到Mybatis的漸變過程,重點(diǎn)講解了為什么要將JDBC封裝成Mybait...
    七寸知架構(gòu)閱讀 76,624評論 36 979
  • 《街角》 作者:陳序 在上海的時(shí)候,喜歡去長樂路。 聽起來是條普通的大街,遠(yuǎn)遠(yuǎn)看去確實(shí)如此,白色的...
    陳序原創(chuàng)閱讀 187評論 0 1
  • ——暖風(fēng)吹拂著過去斑駁的光陰,吹過一段又一段舊時(shí)光 我工作快5年,平時(shí)很節(jié)省花銷很少,還經(jīng)常會(huì)去姨媽家蹭吃蹭喝,順...
    南北繁華閱讀 273評論 0 0