2012-10-25 59 views
0

由於它是不可能只使用Long ID我試圖使用生成的字符串鍵。我有三個類UserTopic,CommentsUser - 1:n - Topic - 1:n - CommentsGAE數據存儲與JPA生成字符串鍵

類註釋:

@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; 

現在,當我牛逼rying保存新的用戶,將出現以下異常

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?如果是,我的代碼有什麼問題?

謝謝

回答

0

我使用TableGenerator。這是有用的,無論你是什麼want id風格。比方說,即使你想獲得Group id,如GRP0000001GRP0000500等。 你必須使用屬性注入,而不是實體注入。它基於你的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; 
    } 
} 

Utils.java

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; 
    } 
} 
+0

不在GAE上,您不 – DataNucleus