I'm new of jpql and I have the following situation.
I have two entities Place and 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.
尝试使用子查询,例如
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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.