Mapper 動態代理方式

來源:互聯網
上載者:User

標籤:space   對應檔   mybatis   編寫   except   value   throw   utf-8   birt   

Mapper介面開發方法只需要程式員編寫Mapper介面(相當於Dao介面),由Mybatis架構根據介面定義建立介面的動態代理對象,代理對象的方法體同上邊Dao介面實作類別方法。

Mapper介面開發需要遵循以下規範:

1、 Mapper.xml檔案中的namespace與mapper介面的類路徑相同。

2、 Mapper介面方法名和Mapper.xml中定義的每個statement的id相同

3、 Mapper介面方法的輸入參數類型和mapper.xml中定義的每個sql 的parameterType的類型相同

4、 Mapper介面方法的輸出參數類型和mapper.xml中定義的每個sql的resultType的類型相同

 

 

Mapper.xml(對應檔)

 

定義mapper對應檔UserMapper.xml(內容同Users.xml),需要修改namespace的值為 UserMapper介面路徑。將UserMapper.xml放在classpath 下mapper目錄 下。

 

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cn.itcast.mybatis.mapper.UserMapper"><!-- 根據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>

 

 

Mapper.java(介面檔案)

 

/** * 使用者管理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; }

 

 使用

//擷取mapper介面的代理對象

UserMapper userMapper = session.getMapper(UserMapper.class);

擷取代理對象後調用其方法完成業務

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.