开发者

JPA: Is there a way to return the next availble PK

if the field id inside my Entity is like this

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
开发者_运维百科

then when I persist the Entity, a unique random Id is created. Is there a way that I can retrieve the next available PK before persist


There isn't in the spec, although some implementations may provide a means. The problem is the ID is generated by the database in some cases, whether by a sequence or a autoincrement. It's too challenging for JPA to know exactly what to do.


Without knowing exactly what you are planning to do with the id when you have it, I found this link that may be helpful. I would write a custom sequence class that just calls the super methods to generate the id but then do what you need to do once you have it.


In EclipseLink you can do this buy,

Number nextId = entityManager.unwrap(Session.class).getNextSequenceNumberValue(MyEntity.class);


@Harry Pham See the Eclipselink User Guide:

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/Ids/GeneratedValue

At the bottom it states what James already said. You can use the following code to obtain the next sequence number value:

long id = em.unwrap(Session.class).getNextSequenceNumberValue(Employee.class).longValue();

The Session class is in package org.eclipselink.persistence.Sessions.

But using this is eclipselink proprietary and not JPA.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜