问题:在我对数据库进行一条插入操作时,我需要对其中的一个字段根据ID内容进行修改,但是我插入了这条数据之后不知道如何把它取出来然后完成修改。
解决方案:Mybatis在插入语句时,有一些可选属性可以返回现在插入数据的自增字段。
原本代码
<!--增-->
<insert id="addProject" parameterType="Project">
INSERT INTO project(<include refid="project_column"/>)
VALUES (<include refid="project_proporties"/>)
</insert>
修改后代码
<!--增-->
<!--keyColumn="id"这条属性可以不加,只是为了防止自增属性不是第一个字段而设置的 keyProperty="id"当这个属性存在时,返回当前递增的ID useGeneratedKeys="true"-->
<insert id="addProject" parameterType="Project" keyColumn="id" keyProperty="id" useGeneratedKeys="true">
INSERT INTO project(<include refid="project_column"/>)
VALUES (<include refid="project_proporties"/>)
</insert>
修改后在Controller层调用时
project.getId();//此时为null
projectService.addProject(project);
project.getId();//此时可获取到ID
当使用的为修改后的代码时,在我们执行了这句SQL语句后,可以获得当前插入的这条数据的ID;
下面是添加的三个字段的详细描述:
useGeneratedKeys
(insert and update only) This tells MyBatis to use the JDBC getGeneratedKeys method to retrieve keys generated internally by the database (e.g.auto increment fields in RDBMS like MySQL or SQL Server). Default: false
(( 仅 对 insert 和update有 用 ) 这 会 告 诉 MyBatis 使 用 JDBC 的 getGeneratedKeys 方法来取出由数据(比如:像 MySQL 和 SQL Server 这样的数据库管理系统的自动递增字段)内部生成的主键。默认值:false。)
keyProperty
(insert and update only) Identifies a property into which MyBatis will set the key value returned by
getGeneratedKeys , or by a selectKey child element of the insert statement. Default: unset .
Can be a comma separated list of property names if multiple generated columns are expected.
((仅对 insert和update有用) 标记一个属性, MyBatis会通过 getGeneratedKeys 或者通过 insert 语句的 selectKey 子元素设置它的值。默认: 不设置。)
keyColumn
(insert and update only) Sets the name of the column in the table with a generated key. This is only required
in certain databases (like PostgreSQL) when the key column is not the first column in the table. Can be a
comma separated list of columns names if multiple generated columns are expected.
((仅对 insert和update有用) 标记一个属性, MyBatis会通过 getGeneratedKeys 或者通过 insert 语句的 selectKey 子元素设置它的值。默认: 不设置。)
备注:
useGeneratedKeys 要求数据库本身具备主键自动增长的功能,比如说,mysql,sqlserver可以使用useGeneratedKeys =true ;但是oracle不支持useGeneratedKeys。请参考下面方法(未实际测试)
参考大神的信息地址