Error : Cannot use identity column key generation with <union-subclass> ( TABLE_PER_CLASS )

Ganapat picture Ganapat · Jan 10, 2014 · Viewed 7.7k times · Source

I am using Hibernate to save entities where all entities are inherited from a base abstract entity. For all concrete Entities there are database tables respectively, with autoincrement primary key column. But using GenerationType as "AUTO" or "IDENTITY" gives error. I want all records in database tables representing each concrete entity class, should have sequentially incremented ID values.

com.something.SuperClass:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class SuperClass implements Serializable {
    private static final long serialVersionUID = -695503064509648117L;

    long confirmationCode;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO) // Causes exception!!!
    public long getConfirmationCode() {
        return confirmationCode;
    }

    public void setConfirmationCode(long confirmationCode) {
        this.confirmationCode = confirmationCode;
    }
}

com.something.SubClass:

@Entity
public abstract class Subclass extends SuperClass {
    private static final long serialVersionUID = 8623159397061057722L;

    String name;

    @Column(nullable = false)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Gives me this exception:

Caused by: org.hibernate.MappingException: Cannot use identity column key
generation with <union-subclass> mapping for: com.something.SuperClass
What's the best and most convenient way for me to generate the ID's? I do not want to change my inheritance strategy.

I know it can be solved if I change GenerationType from "AUTO" to "TABLE", but the issue with this solutions is, generated keys are not in exact sequence. It leaves big gap between keys.

I am looking for solution which will allow all tables to use Auto Incremental values generated by Mysql AutoIncrement primary column.

Thanks in advance to all.

P.S.: I have already gone through following posts: Cannot use identity column key generation with <union-subclass> ( TABLE_PER_CLASS )

Answer