Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use identity column key generation with the strategy TABLE_PER_CLASS in JPA?

This question is in context with the problem mentioned in this thread. I'm also facing the same problem while using JPA on MySQL. I could resolve it only when I changed the generation strategy to TABLE.

But the question is, what was the reason behind this problem and why changing the strategy to TABLE is the solution (this remains unanswered in the thread) ?

like image 434
n_g Avatar asked Jan 07 '12 06:01

n_g


Video Answer


2 Answers

if you want to share some property between class, you can use @MappedSuperclass to the superclass, this will not affect the child class Id generate strategy. it just copy all the annotation to the child class

@MappedSuperclass
public class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(columnDefinition = "TIMESTAMP")
    private Date createTime = new Date();


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}
like image 28
宏杰李 Avatar answered Nov 13 '22 18:11

宏杰李


To have unique ids through an inheritance hierarchy (which JPA requires), you obviously cannot do that with TABLE_PER_CLASS and IDENTITY since IDENTITY works off a table, and there are now multiple "root" tables in the inheritance hierarchy.

e.g abstract base class "Base", and subclasses "Sub1", "Sub2", "Sub3". So you have actual tables "SUB1", "SUB2", "SUB3". So if using IDENTITY then this will equate to something like "autoincrement" on a column when using MySQL. Hence SUB1 has its ids, SUB2 has its ids, and SUB3 has its ids ... and they are independent, hence can get collisions in id ... so you no longer have unique id in the inheritance hierarchy.

like image 197
DataNucleus Avatar answered Nov 13 '22 17:11

DataNucleus