当前位置: 代码迷 >> 综合 >> mybatis的Mapper中在mysql和oracl中新增一条记录,返回记录id
  详细解决方案

mybatis的Mapper中在mysql和oracl中新增一条记录,返回记录id

热度:14   发布时间:2024-01-17 06:31:26.0

情景再现:项目中经常在mybatis的Mapper中在mysql和oracl中新增一条记录后,需要返回记录id:

1.使用mysql数据库:

//java的User对象,包含id,name,password三个属性

<insert id="insert" useGeneratedKeys="true" keyProperty="id"  >

   INSERT INTO user(//id 在这里可以省略name,password) VALUES (#{name},#{password})
</insert>

ps:mysql数据库,表主键id一般设置为自增,从1开始;useGeneratedKeys只针对 insert 语句生效,默认为 false。当设置为 true 时,表示如果插入的表以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键返回;keyProperty是Java对象的属性名。

2.使用oracl数据库:

<insert id="insert">

<selectKey resultType="java.lang.String" order="BEFORE" keyProperty="id">

  select USER_ID_SEQ.nextval as id  from dual          

</selectKey>

INSERT INTO user(id,name,password) VALUES (#{id},#{name},#{password})
</insert>

ps:oracl数据库,表主键一般是用序列进行自增,也是从1开始, order可设置为BEFORE 或 AFTER,当设置为 BEFORE时,它会首先选择主键,设置 keyProperty 然后执行插入语句。当设置为 AFTER,那么先执行插入语句 ;USER_ID_SEQ.nextval 为oracl序列。

  相关解决方案