在存放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();