0

JPA基準APIを使用してSQL演算子と一致する必要があるテーブル内の特定の国名(ではない)にStateTable基づいて州を検索する必要があります(名前が示すように外部キーです)。countryIdCountrylikecountryIdStateTable

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利用可能で、この条件クエリは約です)。CountryStateTable

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

2 に答える 2

4

結合を実行する必要があります:

Join<StateTable, Country> country = root.join("countryId");
predicates.add(criteriaBuilder.like(country.<String>get("countryName"), "%"+countryName+"%"));
于 2013-05-14T10:38:53.137 に答える
1

次のように条件の定義を拡張できます (State エンティティにプロパティ country があると仮定します。つまり、state テーブルの外部キーとして country_id を持っていると仮定します):

Join<StateTable, Country> country = root.join("country", JoinType.LEFT);

// and change predicate with 
predicates.add(cb.like(country.<String>get("countryName"), "%"+countryName+"%"));

これですべての作業が完了するはずです。

于 2013-05-14T09:48:33.017 に答える