我需要在Department和Person之间创建一对多的hibernate关系(一个部门有很多人)。
问题在于我想保持时间有效性。如果没有ORM(休眠),很容易在指定日期选择特定部门的人员:
select * from Person where department_id = ? and ? between validFrom and validTill
如何使用JPA hibernate实现?
class Department {
Long id;
String code;
String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "departmentId")
@OnDelete(action = OnDeleteAction.CASCADE)
private Set<Person> persons = new HashSet<Person>();
}
class Person {
Long id;
String name;
String surname;
Date validFrom;
Date validTill;
}
如果部门时间有效,如何做到这一点?
select P.* from Person P, Deparment d
where d.code = ? and
p.department_id = d.department_id and
? between d.validFrom and d.validTill and
? between p.validFrom and p.validTill
所有具有相同deparment.code的记录都是一个部门。
答案 0 :(得分:1)
您在JPA中执行此操作的方式与使用SQL执行此操作相同。只需将其作为JPQL查询而不是SQL查询:
select p from Person p
inner join p.department d
where d.code = :departmentCode
and :today between d.validFrom and d.validTill
and :today between p.validFrom and p.validTill