Artyom Chernetsov
Artyom Chernetsov

Reputation: 1404

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);

Upvotes: 14

Views: 16711

Answers (2)

uaiHebert
uaiHebert

Reputation: 1912

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.

Upvotes: 11

Desorder
Desorder

Reputation: 1539

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.

Upvotes: 5

Related Questions