简体   繁体   中英

Hibernate populate primary key using database trigger

I am using Hibernate 4.1.0.Final with Spring 3

I have the following in Entity class

@Id
@Column(name = "PROJECT_NO")
@GeneratedValue(strategy=GenerationType.TABLE)
private String projectNumber;

Is it possible to use database trigger to populate the primary key of a table? Or I have to use a CustomGenerator for this?

When I tried the above I have the following exception

org.hibernate.id.IdentifierGenerationException: Unknown integral data type
for ids : java.lang.String

Database trigger doesn't have any sequence, it is using

SELECT NVL (MAX (project_no), 0) + 1 FROM projects

Edit 1

@GeneratedValue(generator="trig")
@GenericGenerator(name="trig", strategy="select", 
parameters=@Parameter(name="key", value="projectNo"))

The above throws the following exception

Hibernate: select PROJECT_NO from PROJECTS where PROJECT_NO =?

java.lang.NullPointerException
exception in save null
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:645)
    at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:4268)
    at org.hibernate.id.SelectGenerator$SelectGeneratorDelegate.bindParameters(SelectGenerator.java:138)
    at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:84)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2764)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3275)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)

The problem is that you're using a String instead of a numeric value. Use a Long instead of a String, and your error will disappear.

AFAIK, you can't use a trigger to populate the ID. Indeed, Hibernate would have to retrieve the generated ID, but since it doesn't have an ID, I don't see how it could read back the row it has just inserted (chicken and egg problem).

You could use your SQL query to get an ID before inserting the row, but this strategy is inefficient, and has a risk of duplicate IDs in case of concurrent inserts. So I wouldn't use this strategy. You tagged your post with Oracle. I suggest you use a sequence. that's what they're for.

As of this on the Hibernate 3.3 documentation page you can do that.

select

retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM