Hibernate, Oracle, Sequences, Triggers

本文探讨了Hibernate在使用Oracle数据库时如何与序列和触发器协同工作以设置主键值,解释了常见的off-by-one问题,并提供了解决方案。
[url=http://www.zhubajie.com/task/?welcome=1523583]有困难,找猪八戒[/url]
请看原文:
[url]http://www.juliesoft.com/blog/jon/index.php/2007/02/19/hibernate-oracle-sequences-triggers-and-off-by-one%E2%80%99s/[/url]


Hibernate, Oracle, Sequences, Triggers, and Off-by-One’s

Posted by jonchase

Hibernate and Oracle triggers may both need to set the primary key value when inserting a row into the database - here’s how to make them play nice together.

Oracle users typically use a combination of a trigger and a sequence to achieve what many databases support natively - the concept of an Identity data type for use in creating primary keys.

Often this is accomplished with something like the following in Oracle:

/* create a simple table */
create table Person (
id number(9) not null,
name nvarchar2(10) );

/* primary key definition on Person.id */
create unique index pk_Person on Person (id);

/* generates a non-repeating (unique) numeric value */
create sequence seq_Person_id;

/* gets called every time a Person row is
inserted to set Person.id to the next value
of seq_Person_id */
create or replace trigger trig_Person_insert
before insert on Person
for each row
begin
select seq_Person_id.NEXTVAL into :new.id from dual;
end;

The above is all well and good - it works great when a client does something like the following:

/* insert a row into Person table */
insert into Person (name) values ("Jon");

The following row would be inserted into the database:

[1, Jon]

And in steps Hibernate to ruin everything.

Let’s assume we have mapped the above table definition to a Person class we have created, like so:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="example.Person" table="Person">
<id name="id">
<generator class="sequence">
<param name="sequence">seq_Person</param>
</generator>
</id>
<property name="name" />
</hibernate-mapping>

Here’s how to insert a new Person row using Hibernate (pseudo code):

Person person = new Person("Julie");
session.save(person);
System.out.println("person.id:" + person.id);

The above code creates a new Person object with a name of “Julie” and then inserts it into the database. Assuming the row with “Jon” has already been inserted into the database, here’s what the program would print out when run:

person.id:2

So you’d assume that the following two rows now exist in the database:

[1, Jon]
[2, Julie]

Right?

Wrong.

There are two rows in the database, that’s for sure, but they look like this:

[1, Jon]
[3, Julie]

3? Did we just discover a bug in Oracle? Are you telling me it can’t get the math right for 1 + 1? Thankfully, Oracle and Hibernate are operating exactly as planned - there’s no bug here. As usual, the devil is in the details.

What’s happening? Why are there two different id values for “Julie”? Why is there a [2] printed out, while the database holds a [3]?

For an explanation, look at the same code one more time, this time with some comments on the steps Hibernate and the Oracle database take when inserting the Person into the database:

Person person = new Person("Julie");
// 1st, Hibernate will make a call to get the next
// value of seq_Person:
// select seq_Person.nextval from dual; -- returns [2]
// 2nd, Oracle will call the trig_Person_insert
// trigger to set the value of id. Note that
// the trigger also uses the sequence to get
// the next value of id (3) and sets the id of
// the new Person row using that value (thus
// overriding the [2] Hibernate will set in the
// insert statement)
// 3rd, Hibernate will use the value it got from
// the sequence (2) when inserting the Person row:
// insert into Person (id, name) values (2, "Julie");
session.save(person);
System.out.println("person.id:" + person.id);

In the case above, even though Hibernate explicitly specified that [2] should be used for the id of the new row, the trigger defined in Oracle trumped Hibernate, and thus the row in the database has a value of [3]. However, Hibernate doesn’t know this, and so it sets the id of the Person object to [2].

Confused yet? Hopefully less that you were before.

Here’s how to fix the issue. Change the trigger definition to the following:

/* gets called every time a Person row is inserted,
but only sets the Person.id if it is not already
specified in the SQL insert statement */
create or replace trigger trig_Person_insert
before insert on Person for each row
begin
if :new.id is null
then select seq_Person_id.NEXTVAL into :new.id from dual;
end if;
end;

Notice that the trigger only sets the id if it’s not already set in the insert statement. After the long explanation of the problem, that’s all there is to the solution. If a user now issues an insert like the following:

insert into Person (name) values ("Marc");

The database will contain the following rows:

[1, Jon]
[3, Julie]
[4, Marc]

And if Hibernate is then used to insert another row:

Person person = new Person("Tony");
session.save(person);

Tthe database will contain the following rows, as expected:

[1, Jon]
[3, Julie]
[4, Marc]
[5, Tony]

One Note

Many relational databases, like SQL Server, MySql, and Db/2 (to name a few) natively support the concept of Identity Columns. That is, to get unique key generation on these platforms, simply declare the id column as an Identity type, and the database will take care of all the id generation for you - no muss no fuss.

Just change the Hibernate mapping we used above for the id column to this:

<id name="id"> <generator class="native">
<param name="sequence">seq_Person</param>
</generator>
</id>

…and Hibernate will pick the appropriate strategy for the database it’s running on - identity for those databases that support it, or the sequence strategies for databases like Oracle.
One More Note

Modification to the trigger isn’t necessary if the ONLY client that is going to be inserting data into the database is Hibernate. In that case, the trigger isn’t necessary at all. Hibernate will use the defined sequence to get a value for id and insert it. The above is useful for the situation where non-Hibernated based clients will be inserting data into the database. This is often common if, say, a web application built using Hibernate is inserting data into the database and a legacy COBOL application is also inserting data into the same database. A strategy like the above will allow both applications (and any others added in the future) to peacefully coexist. However, the peaceful coexistence of your Java and COBOL programmers is another issue altogether.
[url=http://www.zhubajie.com/task/?welcome=1523583]有困难,找猪八戒[/url]
内容概要:本文详细介绍了“秒杀商城”微服务架构的设计与实战全过程,涵盖系统从需求分析、服务拆分、技术选型到核心功能开发、分布式事务处理、容器化部署及监控链路追踪的完整流程。重点解决了高并发场景下的超卖问题,采用Redis预减库存、消息队列削峰、数据库乐观锁等手段保障数据一致性,并通过Nacos实现服务注册发现与配置管理,利用Seata处理跨服务分布式事务,结合RabbitMQ实现异步下单,提升系统吞吐能力。同时,项目支持Docker Compose快速部署和Kubernetes生产级编排,集成Sleuth+Zipkin链路追踪与Prometheus+Grafana监控体系,构建可观测性强的微服务系统。; 适合人群:具备Java基础和Spring Boot开发经验,熟悉微服务基本概念的中高级研发人员,尤其是希望深入理解高并发系统设计、分布式事务、服务治理等核心技术的开发者;适合工作2-5年、有志于转型微服务或提升架构能力的工程师; 使用场景及目标:①学习如何基于Spring Cloud Alibaba构建完整的微服务项目;②掌握秒杀场景下高并发、超卖控制、异步化、削峰填谷等关键技术方案;③实践分布式事务(Seata)、服务熔断降级、链路追踪、统一配置中心等企业级中间件的应用;④完成从本地开发到容器化部署的全流程落地; 阅读建议:建议按照文档提供的七个阶段循序渐进地动手实践,重点关注秒杀流程设计、服务间通信机制、分布式事务实现和系统性能优化部分,结合代码调试与监控工具深入理解各组件协作原理,真正掌握高并发微服务系统的构建能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值