实体是 Tile,在 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 坐标是预定义的,因为没有坐标的 Tile 毫无意义。
Tile tile=new Tile(x,y);
最佳答案
这取决于您的属性具有哪种 ID。
首先,您需要将注释 @Transient
放在 isNew()
方法上。
如果您的 id 是 Long
(或任何其他对象),您可以检查是否 id == null
。如果您的 id 是 long
(或任何其他原语),您将需要检查 id == 0
。
在您发布的实体中,有一个嵌入的ID,并且不要仅执行if Embedded == null的操作,因为JPA会检查属性。
关于jpa - 在Spring Data中为具有预定义ID的实体实现Persistable.isNew的首选方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26313044/