0

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

jmj
  • 232,312
  • 42
  • 391
  • 431
Thang Pham
  • 37,175
  • 74
  • 195
  • 283

4 Answers4

2

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.

Brian Topping
  • 3,107
  • 27
  • 33
1

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.

mR_fr0g
  • 8,134
  • 6
  • 36
  • 53
  • This might be a stupid reason. I was just brainstorm on how I would tackle the problem. I am trying to create user profile. The user allow to upload their picture before click `Create User`. So I want to use the same `userId` for the image name, but I wont know that `userId`, until I `persist` the user. – Thang Pham Jan 08 '11 at 16:50
1

In EclipseLink you can do this buy,

Number nextId = entityManager.unwrap(Session.class).getNextSequenceNumberValue(MyEntity.class);
James
  • 18,495
  • 9
  • 78
  • 139
0

@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.

prockel
  • 253
  • 1
  • 2
  • 10
  • I just did a quick test for an entity with generation strategy "IDENTITY". It did not work for me. `getNextSequenceNumberValue()` returned 0, which was not correct. Maybe it works only under certain circumstances, which are not obvious. – prockel Jun 30 '11 at 09:09
  • 1
    You cannot preallocate an IDENTITY id, it requires an insert. In general I would never recommend IDENTITY, use TABLE or SEQUENCE. – James Jun 30 '11 at 13:46