1

我在为以下 sql 创建条件查询时遇到问题。任何帮助将不胜感激。假设我有两张表成员和人员。我加入了姓名和年龄,并为这两个表添加了 where 子句。我正在使用 OpenJPA(2.0)

select * 
from Member
join Person
on Member.name = Person.name 
    and Member.age = Person.age
where Member.name = 'someOne'
and Member.age = '24'
and Person.gender = 'F'
and Person.type = 'employee' 
4

1 回答 1

0

像这样的东西怎么样:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
Root<Member> fromMember = criteria.from(Member.class);
Root<Person> fromPerson = criteria.from(Person.class);
criteria.multiselect(fromMember, fromPerson);
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(builder.equal(fromMember.get(Member_.name), fromPerson.get(Person_.name)));
predicates.add(builder.equal(fromMember.get(Member_.age), fromPerson.get(Person_.age)));
predicates.add(builder.equal(fromMember.get(Member_.name), "someOne"));
predicates.add(builder.equal(fromMember.get(Member_.age), 24));
predicates.add(builder.equal(fromPerson.get(Person_.gender), "F"));
predicates.add(builder.equal(fromPerson.get(Person_.type), "employee"));
criteria.where(predicates.toArray(new Predicate[predicates.size()]));
List<Tuple> result = em.createQuery(criteria).getResultList();

这将返回一个由 Member 和 Person 组成的 2 元素元组。如果您希望在每个元组中都有单独的字段,您可以在多选调用中枚举单独的字段。

于 2014-03-16T21:50:07.027 回答