2011-05-12 50 views
2

我想生成一個對象的自定義ID,取決於數據庫中已有的值。複雜的主鍵使用休眠與註釋

我知道的幾個問題都是在這個問題上,但我想不出一個解決方案出來......

這裏是我的類:

@Entity 
class A { 
    // primary key for table 
    @GeneratedValue 
    @Id 
    private long tableId; 

    // id -> should be generated as (1+ (max id of type 'type')) 
    @Formula("1+(select t.id from mytable t where t.type=type)") 
    private long id; 

    // type 
    private String type; 
}   

我以爲@Formula註釋,但我不能得到它的工作...

例外提出:

java.sql.SQLException: Field 'id' doesn't have a default value

我不知道@Formula是不錯的解決方案...

有沒有人有我如何使它的工作線索?

非常感謝,

回答

0

我使用@PrePersist批註解決我的問題。

@PrePersist 
private void generateId() { 

    if(id>0){ 
     return; 
    } 
    id=++type.lastChronoId; 
    type.save(); 
} 

將類型修改爲Type類,其中包含最後創建的對象的索引。

1

試試這個

@Formula(value = "(select t.id+1 from mytable t where t.type=type)") 
private long id; 
+0

修正了異常引發,但實際上我誤解了這個註釋的用法:我的「id」字段不再是表列... – Benjamin 2011-05-12 13:23:18