`
zgqynx
  • 浏览: 1364234 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Hibernate, Oracle, Sequences, Triggers

阅读更多
有困难,找猪八戒
请看原文:
http://www.juliesoft.com/blog/jon/index.php/2007/02/19/hibernate-oracle-sequences-triggers-and-off-by-one%E2%80%99s/



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.
有困难,找猪八戒
分享到:
评论

相关推荐

    JEECMS 内容管理系统(hibernate3+struts2+spring2).zip

    **JEECMS 内容管理系统** 是一个基于Java技术栈构建的企业级内容管理解决方案,它采用了经典的SSH(Struts2、Hibernate3、Spring2)框架进行开发。这个系统旨在为各种企业和组织提供灵活、高效的内容发布、管理和...

    Oracle数据库精讲之数据库管理_ Oracle数据库管理视频

    一、课程用到的软件:oracle 11g 二、课程目标: 1. 为有意从事oracle dba工作人员提供学习...第十六讲:oracle sequences管理 第十七讲:oracle 触发器管理 第十八讲:oracle 用户管理 第十九讲:oracle 安装部署管理

    oracle官方文档-Oracle Database Concepts

    3. **数据库对象**:Oracle数据库包含多种对象,如表(Tables)、视图(Views)、索引(Indexes)、序列(Sequences)、存储过程(Stored Procedures)和触发器(Triggers)。它们是数据库应用的基础,满足不同的...

    oracle数据库字段值自动加1

    接下来,需要创建一个序列(Sequences)来生成唯一标识符。在 Oracle 数据库中,序列是一种特殊的数据库对象,用于生成唯一的数字标识符。创建序列的 SQL 语句如下: ``` CREATE SEQUENCE SEQ_EXCELFILE_LINE ...

    Oracle 常用数据字典

    5. DBA_TRIGGERS:该数据字典包含了关于数据库触发器的信息,如触发器名称、触发器类型等。 6. DBA_SYNONYMS:该数据字典包含了关于数据库同义词的信息,如同义词名称、同义词类型等。 7. DBA_SEQUENCES:该数据字典...

    Oracle 数据字典

    这些视图家族包括 COL_PRIVS、EXTENTS、INDEXES、IND_COLUMNS、OBJECTS、ROLE_PRIVS、SEGMENTS、SEQUENCES、SOURCE、SYNONYMS、SYS_PRIVS、TAB_COLUMNS、TAB_PRIVS、TABLES、TRIGGERS、USERS 和 VIEWS 等。...

    Oracle系统表汇总.docx

    通过dba_sequences视图,可以查询序列的基本信息,包括序列名称、序列类型、创建日期等信息。 视图管理 视图是Oracle数据库中的一种虚拟表,用于提供数据的 논리试图。视图管理是Oracle数据库管理系统的重要组件,...

    oracle-pl-sql-programming-5th-edition

    Understand and use new Oracle Database 11g features, including the edition-based redefinition capability, the function result cache, the new CONTINUE statement, fine-grained dependency tracking, ...

    oracle脚本-oracle常用表及数据

    4. **序列**:Oracle数据库中的序列(Sequences)是一种自动增长的数字序列,常用于生成唯一标识符,如主键。序列可以确保在多用户环境下数据的一致性和完整性。例如,可以创建一个名为emp_id_seq的序列,为新插入的...

    Oracle-metadata.rar_metadata oracle_oracle_oracle metadata_oracl

    5. **DBA_TRIGGERS**: 包含数据库中所有触发器的详细信息,这对于理解和管理数据库的业务逻辑很有帮助。 6. **DBA_VIEWS**: 显示所有视图的定义和相关信息,包括视图的SQL查询语句。 7. **DBA_SEQUENCES**: 记录所有...

    Oracle导出数据结构文档.rar

    5. **触发器(Triggers)**:与表相关的触发器定义,包括触发事件(INSERT、UPDATE或DELETE)和触发器代码。 6. **视图(Views)**:视图的SQL查询语句和依赖关系。 7. **存储过程和函数(Procedures and Functions...

    Oracle中主键自增实例

    1. 使用序列(Sequences): Oracle序列是一种数据库对象,可以生成唯一的整数序列。创建序列后,可以在插入新记录时引用它来获取下一个可用的序列值。例如,创建一个名为`SEQ_PRIMARY_KEY`的序列: ```sql CREATE ...

    Oracle Concept 11gR2

    模式对象是指存在于数据库中的数据结构,例如表(tables)、视图(views)、索引(indexes)、序列(sequences)和同义词(synonyms)。这些对象代表了数据存储和组织的方式,对于管理数据库内容至关重要。 表是最...

    SSM框架实体类生成器Generator-Oracle版

    在Oracle数据库中,由于其特性,可能会涉及到如PL/SQL、序列(Sequences)、索引(Indexes)、分区表(Partitioning)等高级特性。当使用Generator时,需要确保这些特性能在生成的实体类中得到正确的映射和处理。...

    ORACLE常用命令.doc

    数据字典中还包括`all_tables`、`all_indexes`、`all_sequences`、`all_constraints`等视图,可以帮助用户查询表、索引、序列和约束的详细信息。通过熟练使用这些视图,可以更高效地管理和监控Oracle数据库。 总之...

    powerdesigner创建oracle_数据库表,设置表主键列为自动增长

    ### PowerDesigner 创建 Oracle 数据库表并设置主键自动增长 #### 一、PowerDesigner与Oracle数据库集成概述 PowerDesigner是一款强大的数据库设计工具,它能够帮助开发者进行数据建模、概念设计以及物理数据库的...

    Oracle sequence 重置(失效恢复)

    FROM user_sequences a, user_constraints b WHERE SUBSTR(a.sequence_name, 5, 100) = b.table_name AND b.constraint_type = 'P' ) LOOP SELECT func_getseq(cur.table_name) INTO max1 FROM DUAL; EXECUTE ...

    Oracle-系统表大全.docx

    select * from dba_sequences; ``` 此语句将返回所有序列的信息,包括序列名称、类型、状态等。 视图管理 视图是 Oracle 数据库中的一个逻辑结构,用于提供一种虚拟的表结构。Oracle 提供了多种方式来管理视图,...

    最完整的Toad For Oracle使用手册

    ### Toad for Oracle 使用手册关键知识点总结 #### 一、简介与新特性 - **Toad for Oracle**:是一款强大的数据库开发与管理工具,适用于Oracle数据库环境。 - **新版本特性**:概述了Toad for Oracle最新版本的...

    java自动生成Oracle sequence管理类

    Oracle自增长主键自动生成类 public static int nextID String table { if table null return 1; table table toLowerCase ; String strKey table; if sequences containsKey strKey { ...

Global site tag (gtag.js) - Google Analytics