mybatis 更新,插入 返回 主键

这个其实是有好几种问题的,先把网上那种先 生成key,再返回的到实体类中的
使用数据库自定义函数nextval(‘student’) ,生成一个key,并把他设置到传入的实体类中的studentId属性上。在执行完此方法后,把该 key 赋值给 studentId属性

  <insert id="createStudent" parameterType="data.model.StudentEntity" keyProperty="studentId">  
        <selectKey keyProperty="studentId" resultType="String" order="BEFORE">  
            select nextval('student')  
        </selectKey>  
        INSERT INTO STUDENT_TBL(STUDENT_ID, STUDENT_SEX,  STUDENT_PHOTO)  
        VALUES (#{studentId},  #{studentSex},    
                #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler})  
    </insert> 

再是一种 ID 是自增长的
这里参数我传入的是 map
设置 useGeneratedKeys=”true” 自增长
keyProperty=”ID” 这个ID 实际就是指的数据库自增长的那个字段,在insert完成后会默认填充给他,执行完成后 在map里面取到对应的key获取value就可以了

<insert id="insertTaxiOrder"   parameterType="map" useGeneratedKeys="true"  keyProperty="ID" > 

      INSERT INTO  tb_TaxiOrderInfo ( UserID, DriverID, StartAddress) 
      VALUES  (#{userID}, 0, #{StartAdd}})
    </insert>

属性 描述 取值
1.keyProperty selectKey 语句生成结果需要设置的属性。

2.resultType 生成结果类型,MyBatis 允许使用基本的数据类型,包括String 、int, map类型。

3.order
3.1:BEFORE,会先选择主键,然后设置keyProperty,再执行insert语句;
3.2:AFTER,就先运行insert 语句再运行selectKey 语句。

4.statementType MyBatis 支持STATEMENT,PREPARED和CALLABLE 的语句形式, 对应Statement ,PreparedStatement 和CallableStatement 响应

猜你喜欢

转载自blog.csdn.net/a520songhai/article/details/80961429