Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if entity is new without checking @Id

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.

like image 793
mjs Avatar asked Aug 04 '15 10:08

mjs


2 Answers

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;
}   
like image 124
Pramod S. Nikam Avatar answered Oct 20 '22 06:10

Pramod S. Nikam


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.

like image 41
André R. Avatar answered Oct 20 '22 05:10

André R.