我是jpql的新手,我有以下情况。
我有两个实体地点和地址。
@Entity
public class Place{
@OneToMany
private List<Address> addresses;
....
}
@Entity
public class Address{
String description;
Date dataFrom;
Date dataTo;
@ManyToOne
private Place place;
....
}
我想获得最后一个地址的描述。 我正在尝试这样做:
select a.description from place p join p.addresses a.....
现在我应该按时间顺序得到最后一个地址。 我该怎么办?
答案 0 :(得分:4)
SELECT addresses.description
FROM place p JOIN p.addresses addresses
ORDER BY addresses.dateFrom
然后将此作为resultList返回并获取列表中的第一项,我会说你可以在T-SQL SELECT TOP 1
中做到,但是,我不相信JPQL支持这个。 / p>
答案 1 :(得分:1)
尝试使用子查询,例如
select a.description from place p join p.addresses a where a.dataFrom = (select max(address.dataFrom) from Address address where address.place = p)
答案 2 :(得分:0)
Criteria criteria = session.createCriteria(Place.class, "place");
criteria.createAlias("place.addresses", "addresses")
criteria.add(Order.desc("addresses.dataFrom"));
criteria.setProjection(Projections.property("addresses"));
List<Address> addresses = criteria.list();
for (Address address : addresses) {
System.out.println(address.description);
}
如果您想根据地点ID使用以下地址找到地址。
Criteria criteria = session.createCriteria(Place.class, "place");
criteria.add(Restrictions.eq("place.id", put the place id here);
criteria.createAlias("place.addresses", "addresses")
criteria.add(Order.desc("addresses.dataFrom"));
criteria.setProjection(Projections.property("addresses"));
List<Address> addresses = criteria.list();
for (Address address : addresses) {
System.out.println(address.description);
}