【问题标题】:JPA Specification with @ManyToMany property具有 @ManyToMany 属性的 JPA 规范
【发布时间】:2021-05-23 07:39:11
【问题描述】:

我有 2 个与 @ManyToMany 关系相关的实体:

public class EntityA {

@Id
private Long id;
.
.
.
@ManyToMany(fetch = fetchType.EAGER)
private List<EntityB> listOfB;

}

我想创建 JPA 规范,该规范将通过 EntityB 的 id 查询 IN 子句。 我试过了

  private static Specification<EntityA> listOfB(String path, List<Long> idsOfB) {
        return (root, query, cb) -> {
            //path is passed as "listOfB"
            return root.get(path).in(idsOfB);
        };
    }

但我得到 org.postgresql.util.PSQLException: ERROR: syntax error at or near "."

【问题讨论】:

    标签: spring-boot hibernate jpa many-to-many


    【解决方案1】:

    您没有显示失败的 SQL,所以我只能猜测出了什么问题。一个可能的问题是 id 列表为空。

    由于您写的是传递listOfB,真正的问题是您将实体与长列表进行比较,这是行不通的。

    您要么需要使用引用对象,即代理,要么使用idsOfB.stream().map(id -&gt; em.getReference(EntityB.class, id)).collect(toList()),或者加入listOfB

    我认为您真正想要的是使用 EXISTS 谓词。像这样的:

    private static Specification<EntityA> listOfB(String path, List<Long> idsOfB) {
        return (root, query, cb) -> {
            Subquery<Integer> subquery = query.subquery(Long.class);
            Root<EntityA> root = subquery.correlate(root);
            subquery.where(root.join(path).get("id").in(idsOfB));
            subquery.select(cb.literal(1L));
            return cb.exists(subquery);
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 2019-05-06
      • 1970-01-01
      相关资源
      最近更新 更多