私は 2 つのエンティティを持っています。
@Entity
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "name", nullable = false, length = 2147483647)
private String name;
@Column(name = "first_name", nullable = false, length = 2147483647)
private String firstName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "peopleId")
private List<PeopleEmail> peopleEmailList;
//... constuctors
//... getters setters
}
およびクラス PeopleEmail
@Entity
public class PeopleEmail implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@NotNull
@Column(name = "email", nullable = false, length = 2147483647)
private String email;
@JoinColumn(name = "people_id", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false)
private Person peopleId;
//... constuctors
//... getters setters
}
ご覧のとおり、両方のエンティティが 1 対多の関係にあります。別のクラスを作成したい:
public class PersonAndCompany{
private String personName;
private String companyName;
private int emailCount;
//... constuctors
//... getters setters
}
そして、PersonAndCompany.class フィールドに個人名と companyName (別のクラス) と電子メール数を入力する typequery を書きたいと思います。ここで、個人の電子メールの数は 2 を超えています。基準 API を使用したいと思います。私はいくつかのコードを書いていますが、PersonAndCompany.class に条件 where を追加して emailcount を埋める方法がわかりません。
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<PersonAndCompany> cq = cb.createQuery(PersonAndCompany.class);
Root<Person> person = cq.from(Person.class);
Join<Person, Company> company = person.join(Person_.companyId);
cq.where(cb.greaterThan(cb.size(person.get(Person_.peopleEmailList)), 2));
Selection<PersonAndCompany> select = cb.construct(PersonAndCompany.class,
person.get(Person_.firstName),
company.get(Company_.name));
cq.select(select);
TypedQuery<PersonAndCompany> query = em.createQuery(cq);
return query.getResultList();