日期:2014-05-16  浏览次数:20615 次

【学习】Mybatis新增后返回主键(MYSQL)
mybatis新增后,返回主键,利用mysql的自有函数LAST_INSERT_ID()。

贴上代码(1)
<insert id="insert" parameterType="com.Test" >
    insert into test(id, username)
    values (#{id,jdbcType=INTEGER},#{username,jdbcType=VARCHAR})
      <selectKey keyProperty="id" resultType="int" order="AFTER">
    	  select LAST_INSERT_ID() 
	  </selectKey> 
  </insert>


其中,test为数据表,字段id为自增主键。

在JAVA程序中写:代码(2)
public void saveTest(Test test){
    this.testMapper.insert(test);//运用mybatis自有接口来新增。
    int id = test.getId();//id值为新增的主键值。
}

在代码(1)中写上了selectKey后,在代码(2)中新增test,test的id属性则自动有了值。