2011-03-10 102 views
16

覆蓋的屬性的通用實體,超類:休眠:如何從映射超類

@MappedSuperclass 
public abstract class GenericEntity { 
    private Integer id; 
    public Integer getId() {return id;} 
    public void setId(Integer id) {this.id = id;} 
} 

的POJO:

@Entity 
@Table(name = "POJO_ONE") 
@SequenceGenerator(name = "HB_SEQ_POJO_ONE", sequenceName = "SEQ_POJO_ONE", allocationSize = 1) 
public class PojoOne extends GenericEntity { 

    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "HB_SEQ_POJO_ONE") 
    @Column(name = "ID") 
    @AttributeOverride(name = "id", column = @Column(name = "ID")) 
    private Integer id; 

    @Override 
    public Integer getId() {return id;} 
} 

我嘗試使用放入系統註釋:@AttributeOverride,@Id, ...但它不起作用。你可以幫我嗎? 我想重寫屬性「id」來指定另一個列名和pojo/table的序列。 這樣做的最好方法是什麼?

+0

http://opensource.atlassian.com/projects/hibernate/browse/HHH-4380 – axtavt

回答

28

試試這個,而不是

@MappedSuperclass 
public abstract class GenericEntity { 
    private Integer id; 
    ... 

    public Integer getId() {return id;} 
    public void setId(Integer id) {this.id = id;} 
} 


@Entity 
@Table(name = "POJO_ONE") 
@SequenceGenerator(name = "HB_SEQ_POJO_ONE", sequenceName = "SEQ_POJO_ONE", allocationSize = 1) 
@AttributeOverride(name = "id", column = @Column(name = "ID")) 
public class PojoOne extends GenericEntity { 
    // we should not define id here again 
    ... 

    @Override 
    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "HB_SEQ_POJO_ONE") 
    public Integer getId() {return id;} 
} 
+0

有了這個解決方案,當我嘗試保存的時候,我有這個例外:'org.hibernate.id.IdentifierGenerationException:這個類的id必須在調用save()之前手動賦值'' – BasicCoder

+0

@ user616564:然後只需要'@GeneratedValue '註釋到'MappedSuperClass',但是子類將無法給出它們自己的實現。如果這對你很好。 –

+0

如何通過表/實體爲id指定一個序列? – BasicCoder

4

爲什麼你不註釋GenericEntity的id@Id? 您也不應該重新定義id,而是將@AttributeOverride(name = "id", column = @Column(name = "ID"))放在課程上而不是字段中。

編輯:

我們在我們的基類中使用這個(package.OurTableGenerator是我們自己的實現):

@GeneratedValue (generator = "ourTableGenerator", strategy = GenerationType.TABLE) 
@GenericGenerator (name = "ourTableGenerator", strategy = "package.OurTableGenerator", 
    parameters = { @Parameter (name = OurTableGenerator.TABLE_PARAM, value = "t_sequence"), 
       @Parameter (name = OurTableGenerator.SEGMENT_COLUMN_PARAM, value = "c_entity"), 
       @Parameter (name = OurTableGenerator.VALUE_COLUMN_PARAM, value = "c_nextHi"), 
       @Parameter (name = OurTableGenerator.INCREMENT_SIZE_COLUMN_PARAM, value = "c_blocksize") }) 
@Id 
@Column(name = "c_uid") 
private Long uid; 

這讓我們指定每個實體/表中的differenc塊的大小和順序。

對於您自己的表格生成器,您可以繼承org.hibernate.id.TableGenerator

+0

我怎麼可以指定表/實體ID的順序? – BasicCoder

+0

我在每個表格中添加了我們用於序列的代碼。 – Thomas

+0

如果你可以發佈類的源代碼OurTableGenerator –