2

我有一个项目有这样的建模:

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

1 回答 1

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();
}

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

于 2013-11-07T18:19:49.787 回答