JPA:如何过滤关联? [英] JPA: How to filter an association?

查看:158
本文介绍了JPA:如何过滤关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模特:

@Entity
class Person {
    @Id
    long id;
    @OneToMany
    Set<Employment> employments =  new HashSet<Employment>();
}

@Entity
class Employment {
    @Id
    long id;
    @ManyToOne
    Company company;
    Date from;
    Date until;
}

这是PersonCompany之间的关联,受时间间隔的限制.

It's an association between a Person and a Company that's restricted by a time interval.

我正在寻找一个JPA标准查询,以选择给定时间的所有Person及其工作.

I'm looking for a JPA criteria query to select all Persons and their employments at a given time.

预期结果是包含 all 人的List<Person>,其中每个Person的集合employments仅包含符合特定条件的工作(或根本没有工作).

The expected result is a List<Person> containing all people, where the collection employments of each Person contains only employments that match certain criteria (or no emplyments at all).

@Where不是明智的方法,因为雇用的筛选条件是可变的,例如我想在任何给定时间选择一个人的所有工作.

@Where is not a sensible approach because the filter criteria for employments is variable, e.g. I would want to select all employments of a person at any given time.

这甚至是合理的事情吗?有什么建议可以采取不同的做法吗?

Is this even a reasonable thing to do? Any suggestions how to do this differently?

推荐答案

不,这不是合理的事情.实体应该表示数据库中的数据,而不是特定查询返回的日期.

No, it's not a reasonable thing to do. An entity is supposed to represent the data that is in the database, and not the date returned by a particular query.

我只需要从EmploymentPerson添加一个ManyToOne关联,然后寻找工作.如果您需要一组人员,则只需遍历各个职业并将每个职业的人员添加到一组中即可.如果您希望在此日期与其工作相关联的人员,则可以使用自定义类或MultiMap<Person, Employment>.

I would simply add a ManyToOne association from Employment to Person, and search for employments. If you need the set of persons, just iterate through the employments and add each employment's person to a Set. If you want the persons associated with their employments at this date, you could use a custom class, or a MultiMap<Person, Employment>.

String hql = "select employment from Employment employment"
             + " left join fetch employment.person"
             + " where :date between employment.startDate and employment.endDate";
List<Employment> employments = session.createQuery(hql)
                                      .setDate("date", date)
                                      .list();

这篇关于JPA:如何过滤关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆