n_g
n_g

Reputation: 3545

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) ?

Upvotes: 6

Views: 4218

Answers (3)

宏杰李
宏杰李

Reputation: 12168

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;
    }
}

Upvotes: 2

smerlin64
smerlin64

Reputation: 130

The accepted answer (although old) is not quite correct. Using GenerationType.IDENTITY does not imply that table generation is used by the DB. The javadoc for GenerationType.IDENTITY says: "Indicates that the persistence provider must assign primary keys for the entity using a database identity column.".

Upvotes: 0

DataNucleus
DataNucleus

Reputation: 15577

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.

Upvotes: 12

Related Questions