JPA基準APIを使用してSQL演算子と一致する必要があるテーブル内の特定の国名(ではない)にStateTable
基づいて州を検索する必要があります(名前が示すように外部キーです)。countryId
Country
like
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; //<-------------------------------
}