简体   繁体   English

Spring 数据 JPA 使用本机查询加载惰性关联

[英]Spring Data JPA load lazy associations using native query

I am querying an entity by using a Postgres specific JSON operator (like @> ).我正在使用 Postgres 特定的 JSON 运算符(如@> )查询实体。 To achieve that, the query needs to be decorated with @Query(nativeQuery = true) .为此,需要使用@Query(nativeQuery = true)修饰查询。 My plan is to fetch the abovementioned entity along with some of its lazy associations.我的计划是获取上述实体及其一些惰性关联。 If I were using JPQL I'd simply JOIN FETCH the entity associations, but in this case I can't.如果我使用的是 JPQL,我只需 JOIN FETCH 实体关联,但在这种情况下我不能。

Please share some suggestions.. thanks请分享一些建议..谢谢

With plain Spring Data, you are out of luck because it is simply so limited.使用普通的 Spring 数据,您就不走运了,因为它是如此有限。 You have to use Hibernate APIs to achieve what you want with a native query.您必须使用 Hibernate API 来实现您想要的原生查询。 There you can specify for a query that you want to materialize some columns for the association of an entity eg在那里,您可以指定要为实体关联的某些列具体化的查询,例如

List<Entity1> list = session.createNativeQuery("select {t1.*}, {t2.*} from tbl1 t1 join tbl2 t2 ...", Entity1.class)
    .addEntity("t1", Entity1.class)
    .addJoin("t2", "t1", "associationName")
    .getResultList();

Alternatively, you can introduce a custom SQLFunction to model this PostgreSQL operator and still continue to use JPQL/HQL.或者,您可以将自定义SQLFunction引入 model 这个 PostgreSQL 运算符,并且仍然继续使用 JPQL/HQL。 See a similar answer for supporting array functions in PostgreSQL: HQL - Check if an Array contains a value请参阅 PostgreSQL 中支持数组函数的类似答案: HQL - 检查数组是否包含值

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

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