[英]GAE Datastore generate String key with JPA
由於無法僅使用長ID,因此我嘗試使用生成的String鍵。 我有三類User
, Topic
, Comments
與User
- 1:N - Topic
- 1:N - Comments
。
類評論:
@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;
班級用戶:
@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來生成String ID? 如果是,我的代碼有什么問題?
謝謝
IIRC IDENTITY策略是生成數字(或密鑰)ID。 如果您使用的是JDO,則可以使用自動生成的UUID樣式的ID。 請參閱https://developers.google.com/appengine/docs/java/datastore/jdo/creatinggettingandandletingdata#Keys
我使用TableGenerator
。 無論您want
id樣式,它都非常有用。 假設即使您想要獲取Group
ID,例如GRP0000001
和GRP0000500
等。您也必須在實體中使用屬性注入,而不是字段注入。 它基於您的setter ID方法。 如果由EntityManager
生成的id為201,則實體管理器將在setter注入中調用setId()
。 如果是這樣,則ID為GRP0000201
。
我的例子:
@Entity
@TableGenerator(name = "GROUP_GEN", table = "ID_GEN", pkColumnName = "GEN_NAME",
valueColumnName = "GEN_VAL", pkColumnValue = "GROUP_GEN", allocationSize = 1)
@Access(value = AccessType.FIELD)
public class Group implements Serializable {
@Transient
private String id;
private String name;
//name getter and setter
public void setId(String id) {
if(id != null) {
this.id = Utils.formatId(id, "GRP", 10);
}
}
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "GROUP_GEN")
@Access(value = AccessType.PROPERTY)
public String getId() {
return id;
}
}
實用工具
public class Utils {
/**
* E.g.
* Input: id=523, prefix="AAA", maxLength=15
* Output: AAA000000000523
*/
public static String formatId(String id, String prefix, int maxLength) {
if (!id.startsWith(prefix)) {
int length = id.length() + prefix.length();
for (; (maxLength - length) > 0; length++) {
id = '0' + id;
}
id = prefix + id;
}
return id;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.