【Mybatis】-mybatis和Mysql返回插入的主键ID

需求:使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的主键值

自增主键返回

思路:
通过mysql函数获取到刚插入记录的自增主键:LAST_INSERT_ID()
执行过程:
执行insert提交之前自动生成一个自增主键,在insert之后调用此函数。
函数解释:
keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性
order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
resultType:指定SELECT LAST_INSERT_ID()的结果类型

<!-- 添加用户 
    parameterType:指定输入 参数类型是pojo(包括 用户信息)
    #{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值
    -->
    <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) value(#{username},#{birthday},#{sex},#{address})
        <!-- 
    </insert>

非自增主键返回

思路:
使用mysql的uuid()函数生成主键,需要修改表中id字段类型为string,长度设置成35位。
执行过程:
首先通过uuid()得到主键,将主键设置到user对象的id属性中,其次在insert执行时,从user对象中取出id属性值
执行uuid()语句顺序相对于insert语句之前执行。

<!-- 添加用户 
    parameterType:指定输入 参数类型是pojo(包括 用户信息)
    #{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值
    -->
    <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
        <!-- 
        将插入数据的主键返回,返回到user对象中
        使用mysql的uuid()生成主键
        执行过程:
        首先通过uuid()得到主键,将主键设置到user对象的id属性中
        其次在insert执行时,从user对象中取出id属性值
         -->
        <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
            SELECT uuid()
        </selectKey>
        insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address})   
    </insert>

猜你喜欢

转载自blog.csdn.net/ldb987/article/details/80724326