mybatis(一) mapper動態代理

來源:互聯網
上載者:User

標籤:update   int   返回   傳參數   set   實體類   簡單   插入   from   

  因為dao開發,會每次建立實體類對象,會傳入id等固定查詢值,存在寫入程式碼問題,所以採用mapper動態代理(不用建立實體類對象,只需要介面,由mapper自動產生)與之前mybatis(一)步驟一樣,但是需要將mapper.xml檔案作出修改:

  namespace:必須是介面類的全路徑 (<mapper namespace="">)

  id:必須是介面的方法名(<select id=""/>)

  parameterType:必須是介面方法裡面的參數類型

  resultType:必須是介面方法的傳回值(若返回list<T>集合類型,則必須是T泛型所代表的實體類)

mapper.xml:

<?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">
<!-- sql語句映射,namespace是為了隔離sql語句 -->
<!-- mapper動態代理方式 -->
<!--namespace與mapper介面的類路徑相同 -->
<!-- mapper介面方法名與mapper的id相同 -->
<!-- mapper介面方法的參數 與 parameterType相同 -->
<!-- mapper介面方法的傳回型別和resultType相同 -->
<mapper namespace="com.xr.mybatis1.User">


<!-- sql查詢操作 ,resultType:結果傳回型別 #{}表示預留位置,可以防止sql注入-->
<select id="selectById" resultType="com.xr.mybatis.User" parameterType="int">
select * from uu where id=#{id}
</select>
<select id="selectByName" resultType="com.xr.mybatis.User" parameterType="java.lang.String">
select * from uu where name like ‘%${value}%‘
</select>


<!-- 插入資料 -->
<insert id="insert" parameterType="com.xr.mybatis.User">
<!-- <selectKey keyProperty="id" order="AFTER">
select LAST_INSERT_ID()
</selectKey> -->
insert into uu(name,money) values(#{name},#{money})
</insert>

<!-- 刪除資料 -->
<delete id="delete">
delete from uu where id=#{id}
</delete>

<!-- 修改資料 -->
<update id="update" parameterType="com.xr.mybatis.User">
update uu set name=#{name} where id=#{id}
</update>
</mapper>

總結:

mybatis 可以解決的jdbc問題:

1:jdbc每次都有載入驅動,建立串連等步驟 ------SqlMapConfig.xml中,使用jdbc事物,串連池處理

2:修改sql語句,就會修改java代碼-----使用mapper,xml檔案,映射sql語句

3:jdbc傳參數太麻煩,因為sql語句的where條件不一定,參數需要和預留位置一一對應-----mybatis自動將java對象映射至sql語句,通過statement中的parameterType指定

4:對結果集解析太麻煩,sql變化將導致解析代碼變化,且解析前需要遍曆-----mybatis自動將sql執行結果映射至java對象,通過statement的resultType指定

mybatis優點:輕量級的架構,簡單,方便,可編寫原生態的sql,控制sql執行效能,靈活度很高。(必須要求編寫sql語句)

 

mybatis(一) 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.