How override getter of id column in jpa configurat

2019-09-20 04:15发布

问题:

This question already has an answer here:

  • Hibernate : How override an attribute from mapped super class 2 answers

I have a problem for @Id in JPA that is described as follow? There is a generic class as follow?

    @MappedSuperclass
    public abstract class BaseEntity<T> implements Serializable {

        private static final long serialVersionUID = 4295229462159851306L;

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

    }

There is another class that extends from it as follow?

@Entity
@Table(name = "DOC_CHANGE_CODE" )
 public class ChangeCode extends BaseEntity<Long> {

     @Id
     @GeneratedValue(generator = "sequence_db", strategy = GenerationType.SEQUENCE)
     @SequenceGenerator(name = "sequence_db", sequenceName = "SEQ_DOC_CHANGE_CODE", allocationSize = 1)     
     public Long getId () {
       return super.getId();
     }
}

Because any sub class has its own sequence, I must specific any subclass @Id, because of that I override the its getter and put some annotations in top of that. Unfortunately it does not work correctly. How do I fix problem and get my goal?

回答1:

Try this:

@Entity
@Table(name = "DOC_CHANGE_CODE" )
@SequenceGenerator(name = "sequence_db", sequenceName = "SEQ_DOC_CHANGE_CODE", allocationSize = 1)     
@AttributeOverride(name = "id", column = @Column(name = "ID"))
public class ChangeCode extends BaseEntity<Long> {

    @Override
    @Id
    @GeneratedValue(generator = "sequence_db", strategy = GenerationType.SEQUENCE)
    public Long getId() {
        return id;
    }
}


回答2:

It's not possible to override the @Id from a base class.

The only way to do it is to provide your own custom IentifierGenerator and provide a different logic based on the subclass (e.g. using a sequence name based on the subclass name).

That's why adding the @Id attribute in the @MappedSuperclass only makes sense for the assigned generator or for IDENTITY.