Hibernate:如何覆盖映射超类中的属性

时间:2011-03-10 09:51:53

标签: java hibernate annotations override mappedsuperclass

通用实体,超类:

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

我尝试使用thoms注释:@AttributeOverride,@ Id,...但它不起作用。你能帮助我吗? 我想覆盖属性“id”以通过pojo / table指定另一个列名和序列。 最好的方法是什么?

2 个答案:

答案 0 :(得分: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;}
}

答案 1 :(得分:4)

为什么不用id注释GenericEntity的@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