How do I override the GenerationType strategy using Hibernate/JPA annotations?

后端 未结 4 1040
野性不改
野性不改 2020-12-29 10:50

I\'m considering using Annotations to define my Hibernate mappings but have run into a problem: I want to use a base entity class to define common fields (including the ID

相关标签:
4条回答
  • 2020-12-29 11:03

    In the code above, it looks like you're mixing annotations on fields (superclass) and methods (subclass). The Hibernate reference documentation recommends avoiding this, and I suspect it might be causing the problem. In my experience with Hibernate, it's safer and more flexible to annotate getter/setter methods instead of fields anyway, so I suggest sticking to that design if you can.

    As a solution to your problem, I recommend removing the id field from your Base superclass altogether. Instead, move that field into the subclasses, and create abstract getId() and setId() methods in your Base class. Then override/implement the getId() and setId() methods in your subclasses and annotate the getters with the desired generation strategy.

    Hope this helps.

    0 讨论(0)
  • 2020-12-29 11:05

    My resolution:

    Refactor the Base class into:

    @MappedSuperclass
    abstract class SuperBase<K> {
        public abstract K getId();
    }
    
    @MappedSuperclass
    class Base<K> extends SuperBase<K> {
        @Id @GeneratedValue(AUTO)
        public K getId() { ... }
    }
    

    Then, you can extends from Base for most of your entity classes, and if one needs to override the @GeneratedValue, just extend from SuperBase and define it.

    0 讨论(0)
  • 2020-12-29 11:09

    On the method in the child dont add the second @Id tag.

    @Override // So that we can set Generated strategy
    @GeneratedValue(strategy = AUTO)
    public Integer getId() {
        return super.getId();
    }
    
    0 讨论(0)
  • 2020-12-29 11:12

    If you put your annotations on the getter rather than the field, when you override the method in the subclass, the annotations placed there will be used rather than the ones in the superclass.

    0 讨论(0)
提交回复
热议问题