我有一个项目有这样的建模:
public abstract class Actor{}
public class Person extends Actor {}
public class Organization extends Actor {}
public abstract class Role{ @ManyToOne @JoinColumn(name="ID_ACTOR") }
public class Customer extends Role{}
public class Employee extends Role{}
我想得到一个List<Role>
扮演特定演员的角色:
public List<Role> getRoles(Actor actor) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Role> criteria = builder.createQuery(Role.class);
//How to do this filter using Criteria API (JPA 2.1)?
return query.getResultList();
}
下面的 SQL 完成了这项工作:
SELECT 'Customer' as role, c.id as id, c.id_actor as actor
FROM customer c
left join person p on p.id = c.id_actor
left join organization o on o.id = c.id_actor
where c.id_actor = ?
UNION
SELECT 'Employee' as role, e.id as id, e.id_actor as actor
FROM employee e
left join person p on p.id = e.id_actor
left join organization o on o.id = e.id_actor
where e.id_actor = ?