Jpa 为Spring数据中具有预定义ID的实体实现Persistable.isNew的首选方法

Jpa 为Spring数据中具有预定义ID的实体实现Persistable.isNew的首选方法,jpa,spring-data,spring-data-jpa,Jpa,Spring Data,Spring Data Jpa,该实体为平铺,在地图上以其坐标唯一标识: import org.springframework.data.domain.Persistable; @Entity class Tile implements Persistable<Tile.Coordinates> { @Embeddable public static class Coordinates implements Serializable { long x; long y;

该实体为平铺,在地图上以其坐标唯一标识:

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
}

我认为没有更好的方法

例如,我想您可以实现一个version列并用1初始化,您的
isNew()
可以
返回version==1


我相信还有其他方法可以做到这一点。

这取决于属性的ID类型

首先,您需要在
isNew()
方法上添加注释
@Transient

如果您的id是一个
Long
(或任何其他对象),您可以检查
id==null
。如果您的id是
长的
(或任何其他原语),则需要检查
id==0

在您发布的实体中有一个嵌入id,不要只执行if embedded==null,因为JPA将检查属性

Tile tile=new Tile(x,y);