由于不可能仅使用长 ID,因此我尝试使用生成的字符串键。我有三个类 User
、Topic
、Comments
和 User
- 1:n - Topic
- 1:n -注释
。
类(class)评论:
@Entity
public class Comment implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
private String key;
@ManyToOne
private User author;
@ManyToOne
private Topic topic;
类(class)用户:
@Entity
public class User implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
private String key;
@Unique
private String username;
类主题:
@Entity
public class Topic implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
private String key;
@ManyToOne(cascade = CascadeType.ALL)
private User author;
@OneToMany(cascade = CascadeType.ALL)
private List<Comment> comments;
现在,当我尝试保存新用户时,出现以下异常
Invalid primary key for User. Cannot have a null primary key field if the field is unencoded and of type String. Please provide a value or, if you want the datastore to generate an id on your behalf, change the type of the field to Long.
是否可以在不手动使用 KeyFactory 的情况下生成字符串 ID?如果是的话我的代码有什么问题吗?
谢谢
最佳答案
IIRC IDENTITY 策略是生成数字(或键)id。 如果您使用 JDO,则可以使用自动生成的 UUID 样式 id。 请参阅https://developers.google.com/appengine/docs/java/datastore/jdo/creatinggettinganddeletingdata#Keys
关于java - GAE 数据存储区使用 JPA 生成字符串 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13066019/