Is there a way to determine given for example entity class:
@Entity
class A {
String name;
}
boolean method(Object anyEntity) {
// How can I check here, if this entity is completely new
}
By new, I mean someone invoked new A() and possibly even set the name, but was never saved, or persisted.
Normally one could check the id, but I want a solution that doest not requires an id, or a getId() method.
Basically, has this entity been persisted to the database, even in detached mode.
@Version or getVersion is also not a satisfactory solution.
Maybe isDetached || isAttached might work, but I am not sure how to make that call on Hibernates API.
EDIT:
Also clarify, I do not control the entities, so I can not add any fields to them. Solution should try to make use of underlying mechanisms to determine this.
If any of API method not available then probably we can achieve it using Listeners:. This will work across JPA/Hibernate.
Like below:
@Transient
private boolean isNew;
@PostPersist
@PostLoad
public void setWhetherNew() {
isNew = true;
}
you could use a transient field and use Entity-Listeners to set this field.
@Transient
private boolean persisted;
@PostLoad
@PostPersist
public void setPersisted() {
persisted=true;
}
you could then use persisted
to tell whether the entity has been ever persisted or not.
-- edit --
@PostLoad
is required so that already persisted entities loaded from the Database also have persisted
set to true. Otherwise they would appear as 'new' even though they could be found in the DB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With