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