2
votes

I'm using the EclipseLink implementation of JPA and I've got a problem.

Here is my entity class:

@Entity
@Table(name = "attendances")
public class Attendance implements Serializable {
private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Short id; ....

In my MySQL table (that is the underlying data store) I have auto_increment flag also set.

How can I get the auto-generated value (id field) before persisting the entity? So if there are 3 entities in the table (id IN (1, 2, 3)), I want to get 4 as the next auto-generated value.

The only workaround I have is:

  1. Get the id of the entity with the largest id field.

Is that all I can do?

1
Why would you like to do that? - JB Nizet
@Nizet I have a dialog for creating an attendance and i want the user to know the id of the attendance that is about to be created. That's not 100% needed by it's said to be helpful. - Daniel Vashchilenko
@JB Nizet: A very valid question, indeed. - Adeel Ansari

1 Answers

0
votes

You can try this, if using JPA 2.0,

entityManagerFactory.getPersistenceUnitUtil().getIdentifier(attendance);

DISCLAIMER: Never tried it myself.

Otherwise, you can change your id generation strategy to something, that can get you the id before persisting the entity. For example, try to use table generator to generate your ids. Here, I found an example, Use Table Generator To Generate ID. Then you would be able to read the value from that table, directly. You may not be able to handle this automatically using @Id, precisely you will end up calculating the next id yourself. Hence, you can employ the same idea but do all the work yourself and set the id while creating the operation, and don't let JPA to generate one.

Or you might like to use the sequence, if supported. In case of sequence also you need to get the next value yourself and set it manually. Be prepared to loose skipped ids in case of no insert, or handle that somehow.

Or you are fine with what you are doing. Just take care of atomicity. Or you may not have the case of multiple transactions running simultaneously.