Spring JPA:如何连接实体中不存在的字段

jmo0nnb3  于 2022-11-14  发布在  Spring
关注(0)|答案(1)|浏览(369)

我们有3个实体A、B和C。我们在表A中搜索B和C中的字段。并且Map是单向的,因此B和Collection未在A中定义。我们使用Spring Specification,在这种情况下,如何在不将Map转换为双向的情况下执行连接?

@Entity
public class A {
    @Id
    Long id
    String name
}

@Entity
public class B {
    @Id
    Long id

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "a_id")
    A a;
    
    @Column
    String country;
}

@Entity
public class C {
    @Id
    Long id

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "a_id")
  private A a;
}

例如,如果B在A中定义为

@Entity
public class A {
    @Id
    Long id
    String name
    
    @OneToOne(mappedBy = "request")
  private B b;
    
}

接合处将是这样

public static Specification<A> countryEquals(String country) {
    return (root, query, builder) -> builder.equal(
        root.join("b", JoinType.LEFT).get("country"), country);
  }

但B未在A中定义,那么如何应用联接?

ubof19bj

ubof19bj1#

您可以尝试通过B本身连接它,创建一个新的Root和Image,在查询中添加一个where b.a_id = a.id,或者在CriteriaBuilder中,然后添加更多 predicate 来查找B表中的字段。

public static Specification<A> countryEquals(String country) {
return (root, query, builder) -> (
    Root<B> b_root = query.from(B.class);
    Predicate b_join = builder.equal(b_root.get("a_id"), root.get("id"))
    Predicate b_country = builder.equal(b_root.get("country"), country) // or like with `%country%`
    return builder.and(other_predicate,...., b_join, b_country)
  )
}

相关问题