mybatis主鍵的生成


<?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">

<!-- namespace命名空間,作用就是對sql進行分類化管理,理解sql隔離
注意:使用mapper代理方法開發,namespace有特殊重要的作用
-->
<mapper namespace="test">
<cache></cache>
<!-- 在 映射文件中配置很多sql語句 -->
<!-- 需求:通過id查詢用戶表的記錄 -->
<!-- 通過 select執行數據庫查詢
id:標識 映射文件中的 sql
將sql語句封裝到mappedStatement對象中,所以將id稱為statement的id
parameterType:指定輸入 參數的類型,這里指定int型
#{}表示一個占位符號
#{id}:其中的id表示接收輸入 的參數,參數名稱就是id,如果輸入 參數是簡單類型,#{}中的參數名可以任意,可以value或其它名稱

resultType:指定sql輸出結果 的所映射的java對象類型,select指定resultType表示將單條記錄映射成的java對象。
-->
<select id="findUserById" parameterType="java.lang.Long" resultType="cn.itcast.mybatis.po.User">
SELECT * FROM USER WHERE id=#{qq}
</select>

<!-- 根據用戶名稱模糊查詢用戶信息,可能返回多條
resultType:指定就是單條記錄所映射的java對象 類型
${}:表示拼接sql串,將接收到參數的內容不加任何修飾拼接在sql中。
使用${}拼接sql,引起 sql注入
${value}:接收輸入 參數的內容,如果傳入類型是簡單類型,${}中只能使用value
-->
<select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User">
SELECT * FROM USER WHERE username like '%${value}%'
</select>

<!-- 添加用戶
parameterType:指定輸入 參數類型是pojo(包括 用戶信息)
#{}中指定pojo的屬性名,接收到pojo對象的屬性值,mybatis通過OGNL獲取對象的屬性值
-->
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<!--
將插入數據的主鍵返回,返回到user對象中

SELECT LAST_INSERT_ID():得到剛insert進去記錄的主鍵值,只適用與自增主鍵

keyProperty:將查詢到主鍵值設置到parameterType指定的對象的哪個屬性
也可以直接在insert中加useGeneratedKeys="true" keyProperty="id"
useGeneratedKeys:表示十是否調用jdbc.useGeneratedKeys方法返回主鍵賦值給keyProperty,默認是false
order:SELECT LAST_INSERT_ID()執行順序,相對於insert語句來說它的執行順序
resultType:指定SELECT LAST_INSERT_ID()的結果類型
-->
<!-- <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
--> <!--
使用mysql的uuid()生成主鍵
執行過程:
首先通過uuid()得到主鍵,將主鍵設置到user對象的id屬性中
其次在insert執行時,從user對象中取出id屬性值
-->

insert into t_test1(id,class_id,name,createDate,updateDate) value(#{id},#{username})


</insert>

<!-- 刪除 用戶
根據id刪除用戶,需要輸入 id值
-->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>

<!-- 根據id更新用戶
分析:
需要傳入用戶的id
需要傳入用戶的更新信息
parameterType指定user對象,包括 id和更新信息,注意:id必須存在
#{id}:從輸入 user對象中獲取id屬性值
-->
<update id="updateUser" parameterType="cn.itcast.mybatis.po.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
where id=#{id}
</update>

</mapper>

 幾種組合的寫法:

(1)<insert id="insertUser"  useGeneratedKeys="true" keyProperty="id" parameterType="cn.itcast.mybatis.po.User">

這樣寫過后就可以在代碼中查到user.getId()

(2)將插入數據的主鍵返回,返回到user對象中

<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM