java mybaits oracle插入返回主键

在MyBatis中,要实现在插入数据后返回主键,可以在Mapper的XML文件中使用useGeneratedKeys属性和keyProperty属性。以下是一个示例:

首先,确保你的Oracle表有一个可以自动生成主键的字段,比如使用Oracle的序列。

sql 复制代码
CREATE TABLE example_table (
  id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  name VARCHAR2(100),
  PRIMARY KEY (id)
);
 
CREATE SEQUENCE example_table_seq START WITH 1 INCREMENT BY 1;

然后,在MyBatis的Mapper XML文件中,你可以这样配置:

sql 复制代码
<insert id="insertExample" useGeneratedKeys="true" keyProperty="id">
  SELECT example_table_seq.NEXTVAL FROM DUAL;
  INSERT INTO example_table (id, name)
  VALUES (example_table_seq.CURRVAL, #{name})
</insert>

或者

sql 复制代码
<mapper namespace="com.example.mapper.YourMapper">  
  
    <!-- 假设你有一个名为YOUR_SEQ的Oracle序列 -->  
  
    <insert id="insertYourEntity" parameterType="com.example.entity.YourEntity">  
        <!-- 先使用selectKey获取序列的下一个值 -->  
        <selectKey keyProperty="id" resultType="java.lang.Long" order="BEFORE">  
            SELECT YOUR_SEQ.NEXTVAL FROM DUAL  
        </selectKey>  
          
        <!-- 然后将获取到的序列值作为主键插入到表中 -->  
        INSERT INTO your_table (id, column1, column2, ...)  
        VALUES (#{id}, #{property1}, #{property2}, ...)  
    </insert>  
  
</mapper>

这里的useGeneratedKeys设置为true表示我们想要获取数据库生成的主键,keyProperty设置为Java对象中的属性名,用于存储主键值。

在Java代码中,你的Mapper接口可能看起来像这样:

java 复制代码
public interface ExampleMapper {
  int insertExample(Example example);
}
 
public class Example {
  private int id;
  private String name;
 
  // getters and setters
}

当你调用insertExample方法并传入一个Example对象时,插入操作执行后,MyBatis会自动将生成的主键值设置到这个对象的id属性中。

相关推荐
郝学胜-神的一滴6 小时前
Python 高级编程 019:类变量与实例变量彻底解析
开发语言·python·程序人生·软件构建
哭哭啼6 小时前
pgSql 事务篇
java·数据库·postgresql
架构源启6 小时前
Spring AI进阶系列(17)- 未来展望与职业发展:Java 工程师迈向 AI 工程化与智能体架构的路线图
java·人工智能·spring
我登哥MVP6 小时前
Spring Boot 从“会用”到“精通”:SpringBoot MVC 请求处理全流程
java·spring boot·后端·spring·mvc·maven·intellij-idea
Thomas_YXQ7 小时前
Unity3D Addressable 深度优化热更性能消耗
开发语言·3d·unity·微信
aini_lovee7 小时前
C# 快递单打印系统(万能套打系统)
开发语言·c#
我登哥MVP7 小时前
Spring Boot 从“会用”到“精通”:ReturnValueHandler原理
java·spring boot·后端·spring·java-ee·maven·intellij-idea
snow@li7 小时前
数据库:MySQL vs PostgreSQL 详尽对比(2026版)
java·mysql·postgresql
天启HTTP7 小时前
开启全局代理后网络变慢,问题出在哪
开发语言·前端·网络·tcp/ip·php