gpt4 book ai didi

jpa - 使用 JPA 条件在另一个表中构建具有搜索条件的搜索查询

转载 作者:行者123 更新时间:2023-12-02 01:11:57 26 4
gpt4 key购买 nike

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

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();

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

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

使用 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;
}

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; //<-------------------------------
}

最佳答案

您需要执行连接:

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

关于jpa - 使用 JPA 条件在另一个表中构建具有搜索条件的搜索查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16538633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com