1

I have setup my classes like below. Hibernate ddl generates 2 tables Admin and Customer. I would have expected only one table as per the SINGLE_TABLE strategy.

@MappedSuperclass
public abstract class BaseUser{
...
}

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Admin extends BaseUser{
...
}


@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Customer extends BaseUser{
@OneToMany
private List<Order> orders;
...
}
DD.
  • 21,498
  • 52
  • 157
  • 246

2 Answers2

1

No, single-table inheritance works differently. The inheritance strategy needs to be defined on the super class. See the JPA Wikibook for reference.

@Entity
@Inheritance
@DiscriminatorColumn(name="USER_TYPE")
@Table(name="USER")
public abstract class BaseUser{
...
}

@Entity
@DiscriminatorValue("A")
public class Admin extends BaseUser{
...
}

@Entity
@DiscriminatorValue("C")
public class Customer extends BaseUser{
@OneToMany
private List<Order> orders;
...
}

Note that depending on your database you may or may not be allowed to call your table USER. There's also an example for how to use @MappedSuperclass.

Marcel Stör
  • 22,695
  • 19
  • 92
  • 198
  • I dont think this is true...the subclasses should inherit the inheritance strategy. In any case this doesn't work either. – DD. Dec 31 '12 at 14:32
-1

This seems to work all though unsure why @MappedSuperclass doesnt.

@Entity
@Inheritance
public abstract class BaseUser{
...
}

@Entity
public class Admin extends BaseUser{
...
}


@Entity
public class Customer extends BaseUser{
@OneToMany
private List<Order> orders;
...
}
DD.
  • 21,498
  • 52
  • 157
  • 246
  • 1
    I told you...it's essentially the same as what I posted (leaving out default configurations). Read up on the link I posted about @MappedSuperclass. It does the exact opposite of what you're after - having a separate table for each sub class (each with columns for the super class fields). – Marcel Stör Dec 31 '12 at 16:53
  • No it's not. I tried your suggestion. I cannot get it to work using @MappedSuperclass even if I define it on the superclass. – DD. Dec 31 '12 at 20:36
  • That must be a misunderstanding. The code in your question uses `@MappedSuperclass` which is wrong. My answer uses `@Inheritance` (and not `@MappedSuperclass`) to produce what you need. The reference in my answer to `@MappedSuperclass` is there to explain how to use it and why it's inappropriate for your scenario. – Marcel Stör Dec 31 '12 at 22:39