views:

145

answers:

3

Hi.

I'm trying to generate a database schema for my project using hbm2ddl. I'm using JPA 2 annotations to specify how the schema should look like. Right now I'm having some issues with inherited id's.

I have an abstract super class, let's call it AbstractSuperClass, which looks like this:

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractSuperClass {
    ...
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public Long getId() {
    }
    ...
}

I've set the id to be an auto generated value which translates to SQL's auto_increment constraint. However when I look at the generated script, I don't see the id columns of the subclass tables to have the auto_increment in them.

Anyone has an idea how I could get that? Of course I could manually specify it but as much as possible I want it automated.

Thanks.

A: 

Note that GenerationType.AUTO means that it's up to the persistence provider to select a generation strategy, have you tried a more specific value?

Tassos Bassoukos
A: 

Not supported, as mentioned in the Reference Documentation in the section about inheritance mapping:

2.2.4.1. Table per class

This strategy has many drawbacks (esp. with polymorphic queries and associations) explained in the JPA spec, the Hibernate reference documentation, Hibernate in Action, and many other places. Hibernate work around most of them implementing this strategy using SQL UNION queries. It is commonly used for the top level of an inheritance hierarchy:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Flight implements Serializable { ... }            

This strategy supports one-to-many associations provided that they are bidirectional. This strategy does not support the IDENTITY generator strategy: the id has to be shared across several tables. Consequently, when using this strategy, you should not use AUTO nor IDENTITY.

Pascal Thivent
A: 

@pascal-thivent I'm not sure how to reply to answers but thanks; I missed that part.

I wonder why that strategy won't support AUTO though. I don't get the part saying,

the id has to be shared across several tables

Why does it have to be shared when each class has its own table?

risc80x86
You should be able to comment answers and you didn't which is why I didn't notice your question :) Suppose you have two subclasses B and C of A and you want to find a A by id (e.g. 1). If both B and C have a record with id=1, who is the "right" one? There is no answer. That's why values of the the identity column in each table must be mutually exclusive when using a "table per class" strategy, which is why IDENTITY (and also AUTO which could default to IDENTITY) is not supported.
Pascal Thivent