【问题标题】:How to create unique IDs for child entities containing Key fields?如何为包含 Key 字段的子实体创建唯一 ID?
【发布时间】:2010-09-07 08:25:39
【问题描述】:

在下面的演示代码中,User 是父实体,与BlogPost 具有一对多关系。

由于BlogPostUser 的子项,其主键字段不能是自动生成的long 值,而必须是使用KeyFactory 实例化的Key 对象。

目前,在为BlogPost 实例化Key 时,我将BlogPost blogTitle(不保证唯一)传递给createKey 方法

但我不知道如何为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);
    }
}

【问题讨论】:

    标签: java google-app-engine


    【解决方案1】:

    您仍然可以使用自动生成的密钥;就用这个:

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
    

    以这种方式生成的 ID 对于给定的父实体将是唯一的,因此要唯一标识帖子,您需要用户对象的 ID 或名称,以及 BlogPost 的 ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 2021-04-30
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多