简体   繁体   English

在本机查询的运行时 (Hibernate/JPA) 临时将 FetchType.LAZY 更改为 FetchType.EAGER

[英]Change FetchType.LAZY to FetchType.EAGER temporary at runtime (Hibernate/JPA) in native query

I have following repository method我有以下存储库方法

@Query(value = "SELECT * FROM property p JOIN address a USING(a_id) JOIN address pa ON p.post_a_id = pa.a_id " +
        "JOIN section s ON s.p_id = p.p_id " +
        "WHERE p.organization_id = :orgId AND p.name ILIKE " +
        "ANY(SELECT UNNEST(ARRAY(SELECT CONCAT('%', UNNEST(STRING_TO_ARRAY(:search, ' ')), '%'))))",
        nativeQuery = true)
Page<Property> findPropertiesByOrganizationIdAndName(@Param("orgId") Long organizationId,
                                                     @Param("search") String search,
                                                     Pageable pageable);

But it gets LazyInitializationException when it tries to get Section entity但是当它试图获取 Section 实体时它会得到 LazyInitializationException

how to dynamically change fetch type of Section enity but with native sql?如何动态更改 Section 实体的提取类型但使用本机 sql?

Property Entity:财产实体:

@Entity
@Table
public class Property extends CreatedDateAuditedEntity {
         @OneToMany(mappedBy = "property", cascade = CascadeType.REMOVE)
         @Fetch(value = FetchMode.SUBSELECT)
         private Set<Section> sections = new HashSet<>();
}

Section entity:部门实体:

@Entity
public class Section extends CreatedDateAuditedEntity {

@ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
@JoinColumn(name = "p_id", referencedColumnName = "p_id", updatable = false, nullable = false)
private Property property;

}

You need to create a CustomDialect that extends from the class of the dialect you are using and in the registrar the functions that you cannot use with JPQL in the following way:您需要创建一个 CustomDialect,它从您正在使用的方言的 class 扩展,并且在注册器中,您不能通过以下方式使用 JPQL 的功能:

 public CustomDialect() {
    super();

    registerFunction(
        "func_custom",
        new StandardSQLFunction(
            "func_custom",
            StandardBasicTypes.STRING
        )
    );
}

and where do you set the dialect:你在哪里设置方言:

<property name="hibernate.dialect" value="your.package.CustomDialect"/>

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

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