Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way to implement Persistable.isNew for entity with predefined ID in Spring Data

The entity is Tile, that uniquely identified with it's coordinates on a map:

import org.springframework.data.domain.Persistable;

@Entity
class Tile implements Persistable<Tile.Coordinates> {
   @Embeddable
   public static class Coordinates implements Serializable {
       long x;
       long y;
       public Coordinates(x,y){this.x=x; this.y=y;}
   }

   @EmbeddedId Coordinates coordinates;

   private Tile(){}
   public Tile(long x,long y) {this.coordinates=new Coordinates(x,y);}

   @Override
   public boolean isNew(){
      // what is preferred implementation? 
   }
   // other code
}

Tile coordinates are predefined, because Tile without coordinates is senseless.

Tile tile=new Tile(x,y);
like image 211
Artyom Chernetsov Avatar asked Oct 11 '14 09:10

Artyom Chernetsov


People also ask

Which method can be used to store records in a database in JPA?

In JPA, we can easily insert data into database through entities. The EntityManager provides persist() method to insert records.

What is Persistable interface in Java?

Many objects in the Web Beans API and the Web Objects API implement the Persistable interface. This interface simplifies the process of maintaining access to objects whose properties have already been set and might be reused at various times throughout the life of a user's session.

How do I stop Spring data JPA from doing a select before a save?

An easy way is to make your Entity implements Persistable (instead of Serializable), which will make you implement the method "isNew".


2 Answers

It depends on which kind of ID your attribute has.

First you will need to put the annotation @Transient on your isNew() method.

If you id is a Long (or any other object) you can check to see if id == null. If your id is a long (or any other primitive) you will need to check if id == 0.

In the entity that you posted there is an embedded id, and do not do only the if embedded == null because the JPA will check the attributes.

like image 148
uaiHebert Avatar answered Sep 27 '22 19:09

uaiHebert


I don't think there is a preferred way.

I guess you could, for example, implement a version column and initialize with 1, your isNew() could return version == 1;

I'm sure there are other ways to do it as well.

like image 45
Desorder Avatar answered Sep 27 '22 17:09

Desorder