If I where you are, I would go with the solution available in the JPA specification, @PostPersist annotation. Your organization will look like this:
@Entity public class entityA { @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; public entityA(){} @PostPersist public void onPersit() {
The Java Persistence 2.1 Specification explains the following features:
The PostPersist and PostRemove callback methods are called on the object after the object has been made permanent or deleted. These callbacks will also be called for all objects to which these operations are cascaded. The PostPersist and PostRemove methods will be called after the database insert and delete operations, respectively. These database operations can be performed immediately after the persist, merge or remove operations were called, or they can occur immediately after the cleanup operation (which may be at the end of the transaction). The generated primary key values ββare available in the PostPersist method.
The above quote also answers your question if the generated primary key is only available after pasting into the database. Your assumption was correct, but it will be available in the annotated @PostPersist method.
Regarding the question of methods for checking an entity for an entity, the naive way is to check if the @Id field @Id null or not. If the code is written in a book (i.e. does not modify the field itself), this will work.
However, for this, there is more complex as suggested in this answer :
@Transient private boolean persisted; @PostLoad @PostPersist public void setPersisted() { persisted = true; }
Using the @PostLoad and @PostPersist , verify that the persisted field is set correctly. Again, you must be sure that you do not change the field outside this method. The @Transient ensures that the field is not a candidate for serialization and, as such, is not constant.
Any of these solutions can be placed in an abstract entity class for reuse for all objects.