开发者

Map superclass and subclass to different tables in Hibernate

I want to map a class to a table and a subclass to another table. I'm not sure if you can do this in a proper way. I tried this so far:

@javax.persistence.Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "MyTable1")
public class MyClass

@javax.persistence.Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "MyTable2")
public class MySubclass extends MyClass

It works but in the generated SQL both tables are joined and I want to keep them seperated.

Another approach was to use the same as above but change JOINED to TABLE_PER_CLASS. This does not work because there is a UNION ALL on both tables in the S开发者_如何学编程QL when I query MyClass.

I also tried to use @org.hibernate.annotations.Entity(polymorphism = PolymorphismType.EXPLICIT) and @org.hibernate.annotations.Entity(polymorphism = PolymorphismType.IMPLICIT) but with no effect.

So my question is if there is a way to map this in Hibernate. Any suggestions?

Thanks!


Using Hibernate 3.6.1


It seems you want to consider the two entities as completely unrelated, except for the fields they have in common. It's not really an inheritance relationship since when you search for a MyClass, you don't want MySubclass instances to be found, although MySubClass instances are instances of MyClass in your design.

The best solution is thus probably to use a MappedSuperclass (see chapter 2.2.4.4) which contains the common fields and methods, and to create two completely separate entities which extend this mapped super class.


TABLE_PER_CLASS should do what you want.

Note that when you execute a query like from MyClass m, Hibernate loads all objects of class MyClass, including subclasses, hence the UNION ALL clause. If you need only MyClass without subclasses, you need to use the following query: from MyClass m where m.class = MyClass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜