简体   繁体   English

将超类和子类映射到Hibernate中的不同表

[英]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. 它可以工作,但在生成的SQL中,两个表都已连接,我希望将它们分开。

Another approach was to use the same as above but change JOINED to TABLE_PER_CLASS. 另一种方法是使用与上面相同的方法,但将JOINED更改为TABLE_PER_CLASS。 This does not work because there is a UNION ALL on both tables in the SQL when I query MyClass . 这不起作用,因为当我查询MyClass时,SQL中的两个表都有UNION ALL。

I also tried to use @org.hibernate.annotations.Entity(polymorphism = PolymorphismType.EXPLICIT) and @org.hibernate.annotations.Entity(polymorphism = PolymorphismType.IMPLICIT) but with no effect. 我还尝试使用@org.hibernate.annotations.Entity(polymorphism = PolymorphismType.EXPLICIT)@org.hibernate.annotations.Entity(polymorphism = PolymorphismType.IMPLICIT)但没有效果。

So my question is if there is a way to map this in Hibernate. 所以我的问题是,是否有办法在Hibernate中映射这个。 Any suggestions? 有什么建议么?

Thanks! 谢谢!


Using Hibernate 3.6.1 使用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. 它不是真正的继承关系,因为当您搜索MyClass时,您不希望找到MySubclass实例,尽管MySubClass实例是您设计中的MyClass实例。

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. 因此,最好的解决方案可能是使用包含公共字段和方法的MappedSuperclass (参见第2.2.4.4节),并创建两个完全独立的实体来扩展此映射的超类。

TABLE_PER_CLASS should do what you want. TABLE_PER_CLASS应该做你想要的。

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. 请注意,当您from MyClass m执行查询时,Hibernate会加载MyClass类的所有对象,包括子类,因此会加载UNION ALL子句。 If you need only MyClass without subclasses, you need to use the following query: from MyClass m where m.class = MyClass . 如果只需要没有子类的MyClass ,则需要使用以下查询: from MyClass m where m.class = MyClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM