java - HIbernate 加载子类和类

标签 java hibernate orm

我正在使用 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/

相关文章:

java - 创建扩展抽象类的子类的实例 (Java)

mysql - admin 不以一对一关系保存在用户表中 spring boot

java - hibernate SQLquery 提取变量

hibernate - ORM 和 DAO - 设计问题

java - @ElementCollection、@CollectionTable 和 Enum - 奇怪的删除/插入行为

java - 避免用户输入出现 NullPointerException

java - 如何在 java 或 netty 中设置套接字选项(TCP_KEEPCNT、TCP_KEEPIDLE、TCP_KEEPINTVL)?

java - 检查 SQS 消息批处理的大小

spring - Tomcat 服务器 : org. apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild:

spring - 使用带有 Spring Data 和绑定(bind)参数的 Postgres JSONB 查询失败并出现 InvalidDataAccessApiUsageException