'Error : Cannot use identity column key generation with <union-subclass> ( TABLE_PER_CLASS )
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 )
Solution 1:[1]
The problem here is that you mix "table-per-class" inheritance and GenerationType.Auto. In a "table-per-class" strategy you use one table per class and each one has an ID.
I Had the same problem and I fixed that by replacing @GeneratedValue(strategy = GenerationType.TABLE) with GenerationType.TABLE
the final code looks like this
@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.TABLE)
public long getConfirmationCode() {
return confirmationCode;
}
public void setConfirmationCode(long confirmationCode) {
this.confirmationCode = confirmationCode;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mehdi Varse |