JPA: How to filter an association?

房东的猫 提交于 2019-12-24 14:32:33

问题


My model:

@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;
}

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

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

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


回答1:


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.

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


来源:https://stackoverflow.com/questions/12563445/jpa-how-to-filter-an-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!