标准多态性如何加入JPA?

时间:2013-10-23 16:13:18

标签: jpa jpa-2.0 criteria-api

我的项目有这样的建模:

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 = ?

1 个答案:

答案 0 :(得分:0)

我解决了在Actor和Role类之间建立双向关系的问题:

public abstract class Actor{ @OneToMany(mappedBy="actor") List<Role> roles }
public class Person extends Actor {}
public class Organization extends Actor {}

public abstract class Role{ @ManyToOne @JoinColumn(name="ID_ACTOR") Actor actor }
public class Customer extends Role{}
public class Employee extends Role{}

这样我就能得到扮演特定演员的List<role>

public List<Role> getRoles(Actor actor) {
    return actor.getRoles();
}

最初我想避免双向关系,但我意识到在这种特殊情况下,有直接的好处