How to create unique IDs for child entities containing Key fields?
In the demo code below, the User
is the parent entity, with a one-to-many relationship with a BlogPost
.
Because the BlogPost
is a child of a User
, its primary key field cannot be an auto-generated long
value but has to be a Key
object instantiated with the KeyFactory
.
At the moment, I am passing the BlogPost
blogTitle
(not guara开发者_C百科nteed unique) to the createKey
method when instantiating a Key
for the BlogPost
But I don't know how to generate a unique ID value for the BlogPost
?
@Entity
public class BlogPost {
@Id
private Key key;
private String blogTitle;
private Text blogText;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
public BlogPost(Key parentKey, String blogTitle) {
this.key = KeyFactory.createKey(parentKey, "BlogPost", blogTitle);
}
}
@Entity
public class User {
@Id
private Key key;
private String username;
private String email;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<BlogPost> blogPosts;
public User(String username){
this.key = KeyFactory.createKey("User", username);
}
}
You can still use an auto-generated key; just use this:
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
IDs generated this way will be unique for a given parent entity, so to uniquely identify a post, you'll need the ID or name of the User object, and the ID of the BlogPost.
精彩评论