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);
In JPA, we can easily insert data into database through entities. The EntityManager provides persist() method to insert records.
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.
An easy way is to make your Entity implements Persistable (instead of Serializable), which will make you implement the method "isNew".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With