【发布时间】:2013-05-14 08:42:13
【问题描述】:
我需要根据Country 表中的给定国家名称(不是countryId)从StateTable 中搜索州,该表应使用JPA 标准API 匹配like 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();
如何修改以下语句以满足需要? (同样countryName 在Country 表中可用,此条件查询是关于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; //<-------------------------------
}
【问题讨论】:
-
你是如何定义Country和StateTable的关系的?无论如何,该解决方案似乎需要加入(使用 JPQL 和 Criteria API)
-
是的,他们俩都有关系。
StateTable有一个外键引用Country的主键。 -
为了给出正确的答案,有必要知道 JPA 中的关系是如何定义的。请编辑您的问题并添加此信息
-
编辑添加实体类。
标签: jpa criteria-api