0

我是 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.....

现在我应该按时间顺序得到最后一个地址。我能怎么做?

4

3 回答 3

4
SELECT addresses.description 
FROM place p JOIN p.addresses addresses 
ORDER BY addresses.dateFrom

然后将其作为 resultList 返回并获取列表中的第一项,我会说您可能可以在 T-SQLSELECT TOP 1中这样做,但是,我不相信 JPQL 支持这一点。

于 2013-10-01T14:14:58.237 回答
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)
于 2013-10-01T20:40:10.307 回答
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);
  }
于 2013-10-01T14:32:38.863 回答