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

泛型实体,超类:

@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的序列。最好的方法是什么?


答案 1

试试这个,代替

@MappedSuperclass
public abstract class GenericEntity {
    protected 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;}
}

答案 2

为什么不用 注释 泛型实体 ?您也不应重新定义,而应将 放在类上,而不是放在字段上。id@Idid@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;

这让我们为每个实体/表指定一个不同的块大小和顺序。

对于您自己的表生成器,您可以子类。org.hibernate.id.TableGenerator


推荐