gpt4 book ai didi

java - HIbernate 加载子类和类

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:31:27 24 4
gpt4 key购买 nike

我正在使用 Hibernate 连接到我的数据库。我的应用程序中有一个继承结构。问题是,当我执行“来自动物”之类的查询时,它会为类动物、其子类以及动物及其子类的所有关联执行左外连接。我该如何避免这种情况。我只想在我的条件查询中通过 fetchmode 指定数据时才加载数据?

最佳答案

是的,Hibernate 支持多态查询。来自文档:

14.8. Polymorphic queries

A query like:

from Cat as cat

returns instances not only of Cat, but also of subclasses like DomesticCat. Hibernate queries can name any Java class or interface in the from clause. The query will return instances of all persistent classes that extend that class or implement the interface. The following query would return all persistent objects:

from java.lang.Object o

The interface Named might be implemented by various persistent classes:

from Named n, Named m where n.name = m.name

These last two queries will require more than one SQL SELECT. This means that the order by clause does not correctly order the whole result set. It also means you cannot call these queries using Query.scroll().

这是默认行为(称为隐式多态性),Hibernate 同时支持隐式显式 多态性:

Implicit polymorphism means that instances of the class will be returned by a query that names any superclass or implemented interface or class, and that instances of any subclass of the class will be returned by a query that names the class itself. Explicit polymorphism means that class instances will be returned only by queries that explicitly name that class. Queries that name the class will return only instances of subclasses mapped inside this <class> declaration as a <subclass> or <joined-subclass>. For most purposes, the default polymorphism="implicit" is appropriate. Explicit polymorphism is useful when two different classes are mapped to the same table This allows a "lightweight" class that contains a subset of the table columns.

这可以在类级别进行配置。使用 polymorphism="explicit"如果您正在使用 xml 映射,请参阅 5.1.3 Class .使用 Hibernate 的 @Entity annotation 如果您正在使用注释,请参阅 2.4.1. Entity .下面是一个例子:

@javax.persistence.Entity
@org.hibernate.annotations.Entity(polymorphism = PolymorphismType.EXPLICIT)
@Inheritance(strategy = InheritanceType.JOINED)
public class Foo {
...
}

关于java - HIbernate 加载子类和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3412896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com