mybatis中Insert后主鍵返回


1.Mapper的寫法,返回的這個int是受影響的行號

int insertNewUser(User newUser);

2.xml的寫法

	<!--返回主鍵 形式1 -->
    <insert id="saveReturnPK1" parameterType="cn.lyn4ever.bean.User" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO `test`.`tb_user`(`username`, age) VALUES(#{username}, #{age})
    </insert>

    	<!-- 返回主鍵 形式2 -->
    <insert id="saveReturnPK2" parameterType="cn.lyn4ever.bean.User">
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT INTO `test`.`tb_user`(`username`, age) VALUES(#{username}, #{age})
    </insert>

3.如何拿到我們剛插入的這個類呢?還是用我們之前插入時的那個newUser,mybatis會給它加上返回的主鍵的,Mapper方法中返回的那個int只是受影響的行號而已,此時,只會返回0或1

newUser.getId();  這個不再是空的了


免責聲明!

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



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