I am using hibernate 4 with criteria API and I am facing a complex query.
My relational model is the following:
What I am trying to do is to get for a given Person all the shipped Articles that belongs to the "n" last ShoppingEvent
before a specified date.
How can I achieve that using criteria API?
nb I already tried something like:
ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("article.articleId"), "articleId");
properties.add(Projections.property("article.price"), "price");
properties.add(Projections.property("article.type"), "type");
return session.createCriteria(Person.class)//
.add(Restrictions.idEq(person.getPersonId()))//
.createAlias("articles", "article")//
.createAlias("article.shoppingEvent", "se")//
.add(Restrictions.le("se.date", currentDate))//
.addOrder(Order.desc("se.date"))//
.setProjection(properties)//
.setResultTransformer(Transformers.aliasToBean(Articles.class))//
.list();
Which returns the articles I want but I don't succeed to use the setMaxResults
to limit the max number of ShoppingEvents
.
It would be easier if you build your query based on the Article, it would be like this:
ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("id"), "articleId");
properties.add(Projections.property("price"), "price");
properties.add(Projections.property("type"), "type");
return session.createCriteria(Article.class)
.createAlias("person", "person")
.createAlias("shoppingEvent", "shoppingEvent")
.add(Restrictions.idEq(person.getPersonId()))
.add(Restrictions.le("shoppingEvent.date", currentDate))
.addOrder(Order.desc("shoppingEvent.date"))
.setProjection(properties)
.setResultTransformer(Transformers.aliasToBean(Articles.class))
.setMaxResults(1)
.uniqueResult();
I mean I get the "n" last Articles but not all the Articles of the last "n" ShoppingEvent
To do this just specify "n" in the .setMaxResults( n )
您可能想尝试一个DetachedCriteria,让它返回上一个ShoppingEvent的“ n”个ID,然后在您的条件中添加一个限制,使您的article.shoppingEvent必须与detachedCriteria中的ID列表匹配。
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.