1. 程式人生 > >java-mybaits-00203-DAO-mapper代理開發方法,多參數【推薦】

java-mybaits-00203-DAO-mapper代理開發方法,多參數【推薦】

tca alt 三種 ram 程序員 spl cep () void

程序員只需要mapper接口(相當 於dao接口) 不需要寫具體實現類,mapper已經代理完成,mybatis才有的

一、mapper代理開發方法(建議使用)

程序員在編寫mapper.xml(映射文件)和mapper.java需要遵循一個開發規範: 1、mapper.xml中namespace就是mapper.java的類全路徑。 2、mapper.xml中statement的id和mapper.java中方法名一致。 3、mapper.xml中statement的parameterType指定輸入參數的類型和mapper.java的方法輸入 參數類型一致。 4、mapper.xml中statement的resultType指定輸出結果的類型和mapper.java的方法返回值類型一致。

二、實現原理

  Mapper接口開發方法只需要程序員編寫Mapper接口(相當於Dao接口),由Mybatis框架根據接口定義創建接口的動態代理對象,代理對象的方法體同上邊Dao接口實現類方法。 總結: 以上開發規範主要是對下邊的代碼進行統一生成: User user = sqlSession.selectOne("test.findUserById", id); sqlSession.insert("test.insertUser", user);

三、開發方法實現

代碼地址:https://github.com/bjlhx15/mybatis 1.Mapper.xml(映射文件)
  定義mapper映射文件UserMapper.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="com.lhx.mybatis.mapperproxy.UserMapper"
> <!-- 根據id獲取用戶信息 --> <select id="findUserById" parameterType="int" resultType="com.lhx.mybatis.po.User"> select * from user where id = #{id} </select> <!-- 自定義條件查詢用戶列表 --> <select id="findUserByUsername" parameterType="java.lang.String" resultType="com.lhx.mybatis.po.User"> select * from user where username like ‘%${value}%‘ </select> <!-- 添加用戶 --> <insert id="insertUser" parameterType="com.lhx.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> <!-- 根據id獲取用戶信息 --> <select id="findUserByIdAndSex" resultType="com.lhx.mybatis.po.User"> select * from user where id = #{0} and sex = #{1} </select> </mapper>
View Code 2.Mapper.java(接口文件) 技術分享
package com.lhx.mybatis.mapperproxy;

import java.util.List;

import com.lhx.mybatis.po.User;

/**
 * 用戶管理mapper
 */
public interface UserMapper {
    // 根據用戶id查詢用戶信息
    public User findUserById(int id) throws Exception;

    // 查詢用戶列表
    public List<User> findUserByUsername(String username) throws Exception;

    // 添加用戶信息
    public void insertUser(User user) throws Exception;
    public User findUserByIdAndSex(int id,int sex) throws Exception;
}
View Code 接口定義有如下特點:
  1. Mapper接口方法名和Mapper.xml中定義的statement的id相同
  2. Mapper接口方法的輸入參數類型和mapper.xml中定義的statement的parameterType的類型相同
  3. Mapper接口方法的輸出參數類型和mapper.xml中定義的statement的resultType的類型相同
3.加載UserMapper.xml文件 在SqlMapConfig-MapperProxy.xml文件中 技術分享
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 和spring整合後 environments配置將廢除 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事務管理 -->
            <transactionManager type="JDBC" />
            <!-- 數據庫連接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                    value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/UserMapper.xml" />
    </mappers>
</configuration>
View Code

四、測試

技術分享
package com.lhx.mybatis.mapperproxy;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import com.lhx.mybatis.po.User;

import junit.framework.TestCase;

public class UserMapperTest extends TestCase {

    private SqlSessionFactory sqlSessionFactory;

    protected void setUp() throws Exception {
        // mybatis配置文件
        String resource = "SqlMapConfig-MapperProxy.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 使用SqlSessionFactoryBuilder創建sessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public void testFindUserById() throws Exception {
        // 獲取session
        SqlSession session = sqlSessionFactory.openSession();
        // 獲取mapper接口的代理對象
        UserMapper userMapper = session.getMapper(UserMapper.class);
        // 調用代理對象方法
        User user = userMapper.findUserById(1);
        System.out.println(user);
        // 關閉session
        session.close();

    }

    public void testFindUserByUsername() throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = userMapper.findUserByUsername("張");
        System.out.println(list.size());

    }

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

    public void testFindUserByIdAndSex() throws Exception {
        // 獲取session
        SqlSession session = sqlSessionFactory.openSession();
        // 獲取mapper接口的代理對象
        UserMapper userMapper = session.getMapper(UserMapper.class);
        // 調用代理對象方法
        User user = userMapper.findUserByIdAndSex(1, 2);
        System.out.println(user);
        // 關閉session
        session.close();

    }
}
View Code

五、總結

  • selectOne和selectList
  動態代理對象調用sqlSession.selectOne()和sqlSession.selectList()是根據mapper接口方法的返回值決定,如果返回list則調用selectList方法,如果返回單個對象則調用selectOne方法。
  • namespace
  mybatis官方推薦使用mapper代理方法開發mapper接口,程序員不用編寫mapper接口實現類,使用mapper代理方法時,輸入參數可以使用pojo包裝對象或map對象,保證dao的通用性。
  • mapper接口方法參數只能有一個是否影響系統 開發【舊版本】
   mapper接口方法參數只能有一個,系統是否不利於擴展維護。   系統 框架中,dao層的代碼是被業務層公用的。    即使mapper接口只有一個參數,可以使用包裝類型的pojo滿足不同的業務方法的需求。 註意:持久層方法的參數可以包裝類型、,map。。。,service方法中建議不要使用包裝類型(不利於業務層的可擴展,沒人知道map要得是什麽參數)。
  • 多個參數的支持

第一種、索引方式

在mapper接口中定義

public User findUserByIdAndSex(int id,int sex) throws Exception;

在mapper.xml中使用

    <!-- 多個參數,不寫入參類型 -->
    <select id="findUserByIdAndSex" resultType="com.lhx.mybatis.po.User">
        select * from user
        where id = #{0} and sex = #{1}
    </select>

第二種、註解參數

在mapper接口中定義

public User findUserByIdAndSex2(@Param("id") int id, @Param("sex") int sex) throws Exception;

在mapper.xml中使用

    <select id="findUserByIdAndSex2" resultType="com.lhx.mybatis.po.User">
        select * from user
        where id = #{id} and sex = #{sex}
    </select>

第三種、map

第四種、po類

  • mapper接口和mapper.xml不支持方法的重載

java-mybaits-00203-DAO-mapper代理開發方法,多參數【推薦】