在下面的演示代码中,User
是父实体,与 BlogPost
具有一对多关系。
由于 BlogPost
是 User
的子级,因此其主键字段不能是自动生成的 long
值,而必须是使用 KeyFactory
实例化的 Key
对象。
目前,在实例化 Key 时,我将
用于 BlogPost
blogTitle
(不保证唯一)传递给 createKey
方法BlogPost
但我不知道如何为 BlogPost
生成唯一的 ID 值?
@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);
}
}
最佳答案
您仍然可以使用自动生成的 key ;只需使用这个:
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
以这种方式生成的 ID 对于给定的父实体来说是唯一的,因此为了唯一地标识帖子,您需要 User 对象的 ID 或名称,以及 BlogPost 的 ID。
关于java - 如何为包含Key字段的子实体创建唯一ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3656973/