-1

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?

reza ramezani matin
  • 1,384
  • 2
  • 18
  • 41

2 Answers2

0

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;
    }
}
Gal Shaboodi
  • 744
  • 1
  • 7
  • 25
0

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.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • I remove @MappedSuperclass from Generic class and override getter of any filed that i want to be in my entity.It works. Is it correct solution? – reza ramezani matin Nov 30 '17 at 10:15
  • If you removed `@MappedSuperclass`, no property will be inherited, so of course, it works. However, there is no reason why you should keep the base class anymore. – Vlad Mihalcea Nov 30 '17 at 10:57
  • @VladMihalcea why this is work ? https://stackoverflow.com/questions/8589928/mappedsuperclass-change-sequencegenerator-in-subclass – ali akbar azizkhani Dec 04 '17 at 16:14