Mapper.xml 配置
在插入标签中添加 useGeneratedKeys="true"
与 keyProperty="id"
属性就可以了,Mybatis 会将自动增长的 id 填入,作为输入参数传入的实体Bean中。
<mapper namespace="book">
<insert id="insertBook" parameterType="bean.BookBean" useGeneratedKeys="true" keyProperty="id">
INSERT INTO t_book(`name`) VALUE(#{name});
</insert>
</mapper>
代码
public void insertBook(BookBean bean) {
SqlSession session = MybaitsUtil.getSqlSession(true);
try {
session.insert("book.insertBook", bean);
// id 会自动填入 bean 中
System.out.println("自增长id为:" + bean.getId());
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
网友评论