Search code examples
javajpamappedsuperclass

JPA @MappedSuperclass different Id counters for subclasses


I've got a @MappedSuperclass which is my base-class for all my entities (@Entity, direct or indirect through multiple sub-classing).

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@XmlAttribute(required = true)
private Long primaryKey;

The Id is generated like shown above.

My problem is that the @Id-counter is the same for each @Entity. In fact thats not a big problem because it would take a while to reach the Long.MAX_VALUE. But reaching that maximum value is a lot easier because there is only one counter for all entities. How can I use a different @Id-counter without having to add the above code to all @Entity-classes?

(If it matters for your answer: I'm using a H2-Database.)


Solution

  • If your database and tables support AUTO_INCREMENT change the annotation to this @Id @GeneratedValue(strategy=GenerationType.IDENTITY). Then the id will be generated during commit.

    There is another way via TABLE or SEQUENCE strategy, but it needs to be explicitly defined per Entity which is problem for abstract BaseEntity. Just hava a look:

    @Entity
    @TableGenerator(name="tab", initialValue=0, allocationSize=50)
    public class EntityWithTableId {
        @GeneratedValue(strategy=GenerationType.TABLE, generator="tab")
        @Id long id;
    }
    

    EDIT: Well, so it is possible! MappedSuperclass - Change SequenceGenerator in Subclass