在存放sql的mapper.xml文件中 插入标签上增加
useGeneratedKeys=”true” keyProperty=”id”
useGeneratedKeys 取值范围true|false 默认值是:false。 含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。
当执行插入时,传入一个实体book,在执行完毕之后,使用book.getId()获取id
相关代码
1.xml
<insert id="insertSelective" parameterType="Entity.Books" useGeneratedKeys="true" keyProperty="id">
insert into bookanswers
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="departno != null" >
departno,
</if>
<if test="isdel != null" >
isdel,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="departno != null" >
#{departno,jdbcType=VARCHAR},
</if>
<if test="isdel != null" >
#{isdel,jdbcType=SMALLINT},
</if>
</trim>
</insert>
2.BookContorller.java
Books book= new Books();
book.setIsdel(0);
bookService.insertBook(book);
int id = book.getId();