【问题标题】:Complex query using Criteria API in Hibernate 4在 Hibernate 4 中使用 Criteria API 进行复杂查询
【发布时间】:2019-02-05 05:30:29
【问题描述】:

我正在使用带有条件 API 的 hibernate 4,我面临一个复杂的查询。

我的关系模型如下:

我要做的是为给定的人获取在指定日期之前属于“n”最后一个ShoppingEvent的所有已发货文章

如何使用标准 API 实现这一点?

n.b. 我已经尝试过类似的方法:

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();

返回我想要的文章但我没有成功使用setMaxResults来限制ShoppingEvents的最大数量。

【问题讨论】:

  • “我无法使用 setMaxResults”是什么意思?你有错误吗?或者你添加它并且它不适用并且返回超过你的 maxResults ?
  • 感谢您的回复,我的意思是我得到了最后“n”篇文章,但不是最后“n”篇购物活动的所有文章

标签: java hibernate criteria


【解决方案1】:

您可能想尝试 DetachedCriteria,让它返回您最后“n”个 ShoppingEvent 的 id,然后在您的条件中添加一个限制,即您的 article.shoppingEvent 必须与您 detachedCriteria 中的 id 列表匹配。

【讨论】:

    【解决方案2】:

    如果您基于文章构建查询会更容易,它会是这样的:

    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();
    

    我的意思是我得到了最后“n”篇文章,但不是所有文章 最后“n”个购物活动

    为此,只需在 .setMaxResults(n)

    中指定“n”

    【讨论】:

    • 感谢您的回复。我必须修改不一致的映射才能做到这一点(我在 Article 实体中添加了关系 @ManyToOne 人,这是以前不存在的)。但即使这样,我也只能得到最后的“n”篇文章。但我要检索的是 all 最后“n” ShoppingEvent 的文章
    猜你喜欢
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多