Hibernate : How override an attribute from mapped super class

无人久伴 提交于 2019-11-26 09:02:08

问题


The generic entity, super class:

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

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

I try to use thoses annotations : @AttributeOverride, @Id, ... but It doesn\'t work. Can you help me? I want to override the attribute \"id\" to specify another column name and a sequence by pojo/table. What is the best way to do that?


回答1:


Try this, instead

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



回答2:


Why don't you annotate the id of GenericEntity with @Id? You also should not redefine id but put the @AttributeOverride(name = "id", column = @Column(name = "ID")) on the class rather than a field.

Edit:

We're using this in our base class (package.OurTableGenerator is our own implementation):

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

This let's us specify a differenc block size and sequence per entity/table.

For your own table generator you could subclass org.hibernate.id.TableGenerator.



来源:https://stackoverflow.com/questions/5257921/hibernate-how-override-an-attribute-from-mapped-super-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!