案例:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.accp.mybatis.model.Blog"> <insert id="insertBlog" parameterType="Blog"> insert into Blog (id,title,author_id) values (#{id},#{title},#{authorId}) </insert> </mapper>
对于insert如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),那么你可以设置 useGeneratedKeys=”true”,然后把keyProperty 设成对应的列,就搞定了。
例如Blog表已经对 id 使用了自动生成的列类型,那么语句如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.accp.mybatis.model.Blog"> <insert id="insertBlog" parameterType="Blog" useGeneratedKeys=”true” keyProperty=”id”> insert into Blog (title,author_id) values (#{title},#{authorId}) </insert> </mapper>
还可以使用selectKey元素。下面例子,使用mysql数据库nextval('student')为自定义函数,用来生成一个key。
例如:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.accp.mybatis.model.Blog"> <insert id="insertBlog" parameterType="Blog" > <selectKey keyProperty="studentID" resultType="String" order="BEFORE"> select nextval('id') </selectKey> insert into Blog (id,title,author_id) values (#{id},#{title},#{authorId}) </insert> </mapper>
insert语句属性配置细节: