[英]One-To-Many query jpql
I'm new of jpql and I have the following situation. 我是jpql的新手,并且遇到以下情况。
I have two entities Place and address. 我有两个实体Place和address。
@Entity
public class Place{
@OneToMany
private List<Address> addresses;
....
}
@Entity
public class Address{
String description;
Date dataFrom;
Date dataTo;
@ManyToOne
private Place place;
....
}
I would want to get the description of the last address. 我想获取最后一个地址的描述。 I'm trying to do this :
我正在尝试这样做:
select a.description from place p join p.addresses a.....
and now i should get the last the last address in order of time. 现在我应该按时间顺序获取最后一个地址。 How can I do?
我能怎么做?
SELECT addresses.description
FROM place p JOIN p.addresses addresses
ORDER BY addresses.dateFrom
Then return this as a resultList and get the first item on the list, I would say you might be able to do like in T-SQL SELECT TOP 1
, however, I don't believe JPQL supports this. 然后将其作为resultList返回并获得列表中的第一项,我想您也许可以像在T-SQL
SELECT TOP 1
,但是,我不相信JPQL支持这一点。
尝试使用子查询,例如
select a.description from place p join p.addresses a where a.dataFrom = (select max(address.dataFrom) from Address address where address.place = p)
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);
}
if you want to find the addresses based on the place id use below one. 如果要根据位置ID查找地址,请在下面使用1。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.