当前位置: 首页 > MySQL数据库

mybatis实现oracle主键自增的机制是什么

时间:2026-01-26 14:21:03

首先我们看对于同一张student表,对于mysql,sql server,oracle中它们都是怎样创建主键的

在mysql中

createtableStudent(Student_IDint(6)NOTNULLPRIMARYKEYAUTO_INCREMENT,Student_Namevarchar(10)NOTNULL,Student_Ageint(2)NOTNULL);insertintostudent(student_name,student_age)values('zhangsan',20);

在sql server中

createtableStudent(Student_IDintprimarykeyidentity(1,1),Student_Namevarchar2(10)NOTNULL,Student_Agenumber(2)NOTNULL);insertintostudent(student_name,student_age)values('zhangsan',20);

在oracle中

createtableStudent(Student_IDnumber(6)NOTNULLPRIMARYKEY,Student_Namevarchar2(10)NOTNULL,Student_Agenumber(2)NOTNULL);

而oracle如果想设置主键自增长,则需要创建序列

CREATESEQUENCEstudent_sequenceINCREMENTBY1NOMAXVALUENOCYCLECACHE10;insertintoStudentvalues(student_sequence.nextval,'aa',20);

  如果使用了触发器的话,就更简单了

createorreplacetriggerstudent_triggerbeforeinsertonstudentforeachrowbeginselectstudent_sequence.nextvalinto:new.student_idfromdual;endstudent_trigger;/

此时插入的时候触发器会帮你插入id

insertintostudent(student_name,student_age)values('wangwu',20);

  至此,mysql,sql server,oracle中怎样创建表中的自增长主键都已完成。

  看一看出oracle的主键自增较mysql和sql sever要复杂些,mysql,sqlserver配置好主键之后,插入时,字段和值一一对应即可,数据库就会完成你想做的,但是在oracle由于多了序列的概念,如果不使用触发器,oracle怎样实现主键自增呢?

<insertid="add"parameterType="Student">  <selectKeykeyProperty="student_id"resultType="int"order="BEFORE">selectstudent_sequence.nextvalfromdual</selectKey>insertintostudent(student_id,student_name,student_age)values(#{student_id},#{student_name},#{student_age})</insert>

  或者

<insertid="save"parameterType="com.threeti.to.ZoneTO"><selectKeyresultType="java.lang.Long"keyProperty="id"order="AFTER">SELECTSEQ_ZONE.CURRVALASidfromdual</selectKey>insertintoTBL_ZONE(ID,NAME)values(SEQ_ZONE.NEXTVAL,#{name,jdbcType=VARCHAR})</insert>

MyBatis 插入时候获取自增主键方法有二

  以MySQL5.5为例:

  方法1:

<insertid="insert"parameterType="Person"useGeneratedKeys="true"keyProperty="id">insertintoperson(name,pswd)values(#{name},#{pswd})</insert>

  方法2:

<insertid="insert"parameterType="Person"><selectKeykeyProperty="id"resultType="long">selectLAST_INSERT_ID()</selectKey>insertintoperson(name,pswd)values(#{name},#{pswd})</insert>

  插入前实体id属性为0;

  插入后实体id属性为保存后自增的id。


上一篇:mysql如何把表名改成大写
下一篇:mysql source导入乱码如何解决
mybatis oracle
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素