使用 JPA 条件在另一个表中使用搜索条件构建搜索查询

Tin*_*iny 2 jpa criteria-api

我需要StateTable根据表中给定的国家/地区名称(不是countryId)搜索州Country,该名称应like使用 JPA 标准 API 与 SQL 运算符匹配(顾名思义,countryId是外键)。StateTable

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<StateTable> criteriaQuery = criteriaBuilder
                                          .createQuery(StateTable.class);
Root<StateTable>root=criteriaQuery.from(StateTable.class);

List<Predicate>predicates=new ArrayList<Predicate>();

predicates.add(criteriaBuilder
          .like(root.<String>get("countryName"), "%"+countryName+"%"));

criteriaQuery.where(predicates.toArray(new Predicate[0]));

entityManager.createQuery(criteriaQuery)
             .setFirstResult(first)
             .setMaxResults(pageSize)
             .getResultList();
Run Code Online (Sandbox Code Playgroud)

如何修改以下语句以满足需要?(同样countryName在表中可用Country,并且此条件查询是关于StateTable)。

predicates.add(criteriaBuilder
          .like(root.<String>get("countryName"), "%"+countryName+"%"));
Run Code Online (Sandbox Code Playgroud)

使用 JPQL 很乏味,因为需要为多个搜索条件构建查询。这只是一个演示/说明。


实体Country

@Entity
public class Country implements Serializable {
    @Id
    private Long countryId;             //<----------------------
    @Column(name = "country_name")
    private String countryName;
    @Column(name = "country_code")
    private String countryCode;
    @OneToMany(mappedBy = "countryId", fetch = FetchType.LAZY)
    private Set<StateTable> stateTableSet;
}
Run Code Online (Sandbox Code Playgroud)

实体StateTable

@Entity
public class StateTable implements Serializable {
    @Id
    private Long stateId;
    @Column(name = "state_name")
    private String stateName;
    @JoinColumn(name = "country_id", referencedColumnName = "country_id")
    @ManyToOne(fetch = FetchType.LAZY)
    private Country countryId;                //<-------------------------------
}
Run Code Online (Sandbox Code Playgroud)

per*_*ssf 5

您需要执行连接:

Join<StateTable, Country> country = root.join("countryId");
predicates.add(criteriaBuilder.like(country.<String>get("countryName"), "%"+countryName+"%"));
Run Code Online (Sandbox Code Playgroud)