我需要StateTable
根据表中的给定国家名称(不是countryId
)搜索状态,该名称Country
应该使用 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
表中可用,此条件查询是 about 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; //<-------------------------------
}