使用 Hibernate Criteria 获取具有最大 id 的记录

发布于 2024-09-26 16:22:43 字数 822 浏览 0 评论 0原文

使用 HibernateCriteria API,我想选择表中给定列具有最大值的记录。

我尝试使用 投影,< a href="http://docs.jboss.org/hibernate/core/4.3/javadocs/org/hibernate/Criteria.html#createAlias(java.lang.String,%20java.lang.String)" rel="noreferrer ">为 max(colunName) 创建别名,然后在 restrictions.eq(),但是它一直告诉我“号码无效”。

使用 Hibernate 执行此操作的正确方法是什么?

Using Hibernate's Criteria API, I want to select the record within a table with the maximum value for a given column.

I tried to use Projections, creating an alias for max(colunName), then using it in restrictions.eq(), but it keeps telling me "invalid number".

What's the correct way to do that with Hibernate?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

菩提树下叶撕阳。 2024-10-03 16:22:43

您可以使用 DetachedCriteria 来表达子查询,如下所示:

DetachedCriteria maxId = DetachedCriteria.forClass(Foo.class)
    .setProjection( Projections.max("id") );
session.createCriteria(Foo.class)
    .add( Property.forName("id").eq(maxId) )
    .list();

参考资料

You can use a DetachedCriteria to express a subquery, something like this:

DetachedCriteria maxId = DetachedCriteria.forClass(Foo.class)
    .setProjection( Projections.max("id") );
session.createCriteria(Foo.class)
    .add( Property.forName("id").eq(maxId) )
    .list();

References

野稚 2024-10-03 16:22:43

我发现同时使用 addOrdersetMaxResults 对我有用。

Criteria c = session.createCriteria(Thingy.class);
c.addOrder(Order.desc("id"));
c.setMaxResults(1);
return (Thingy)c.uniqueResult();

使用 MySQL 方言,这会生成一个类似这样的 SQL 准备语句(剪掉一些字段):

select this_.id ... from Thingy this_ order by this_.id desc limit ?

我不确定此解决方案是否对 MySQL 以外的方言有效。

I found that using addOrder and setMaxResults together worked for me.

Criteria c = session.createCriteria(Thingy.class);
c.addOrder(Order.desc("id"));
c.setMaxResults(1);
return (Thingy)c.uniqueResult();

Using the MySQL dialect, this generates a SQL prepared statement about like this (snipping out some of the fields):

select this_.id ... from Thingy this_ order by this_.id desc limit ?

I am not sure if this solution would be effective for dialects other than MySQL.

半枫 2024-10-03 16:22:43

仅使用

addOrder(Order.desc("id"))

并获取第一个结果:)

Use

addOrder(Order.desc("id"))

and fetch just the first result :)

ゃ懵逼小萝莉 2024-10-03 16:22:43

HQL:

from Person where person.id = (select max(id) from Person)

未经测试。您的数据库需要理解 where 子句中的子选择。

懒得去了解是否/如何使用标准 api 来表达这样的子选择。当然,您可以执行两个查询:首先获取最大 id,然后获取具有该 id 的实体。

HQL:

from Person where person.id = (select max(id) from Person)

Untested. Your database needs to understand subselects in the where clause.

Too lazy to find out if/how such a subselect can be expressed with the criteria api. Of course, you could do two queries: First fetch the max id, then the entity with that id.

南街九尾狐 2024-10-03 16:22:43

更清洁的解决方案也是:

DetachedCriteria criteria = DetachedCriteria.forClass(Foo.class).setProjection(Projections.max("id"));
Foo fooObj =(Foo) criteria.getExecutableCriteria(getCurrentSession()).list().get(0);

The cleaner solution would also be :

DetachedCriteria criteria = DetachedCriteria.forClass(Foo.class).setProjection(Projections.max("id"));
Foo fooObj =(Foo) criteria.getExecutableCriteria(getCurrentSession()).list().get(0);
笑看君怀她人 2024-10-03 16:22:43
    Date maxDateFromDB = null;
    Session session = (Session) entityManager.getDelegate();
//Register is and Entity and assume maxDateFromDB is a column.
//Status is another entity with Enum Applied.
//Code is the Parameter for One to One Relation between Register and Profile entity.
    Criteria criteria = session.createCriteria(Register.class).setProjection(Projections.max("maxDateFromDB") )
    .add(Restrictions.eq("status.id", Status.Name.APPLIED.instance().getId()));
    if(code != null && code > 0) {
        criteria.add(Restrictions.eq("profile.id", code));
    }
    List<Date> list = criteria.list();

    if(!CollectionUtils.isEmpty(list)){
        maxDateFromDB = list.get(0);
    }
    Date maxDateFromDB = null;
    Session session = (Session) entityManager.getDelegate();
//Register is and Entity and assume maxDateFromDB is a column.
//Status is another entity with Enum Applied.
//Code is the Parameter for One to One Relation between Register and Profile entity.
    Criteria criteria = session.createCriteria(Register.class).setProjection(Projections.max("maxDateFromDB") )
    .add(Restrictions.eq("status.id", Status.Name.APPLIED.instance().getId()));
    if(code != null && code > 0) {
        criteria.add(Restrictions.eq("profile.id", code));
    }
    List<Date> list = criteria.list();

    if(!CollectionUtils.isEmpty(list)){
        maxDateFromDB = list.get(0);
    }
夏の忆 2024-10-03 16:22:43

完全使用独立标准来完成此操作(因为我喜欢在没有会话的情况下构建独立标准)

DetachedCriteria maxQuery = DetachedCriteria.forClass(Foo.class)
    .setProjection( Projections.max("id") );
DetachedCriteria recordQuery = DetachedCriteria.forClass(Foo.class)
    .add(Property.forName("id").eq(maxId) );

To do it entirely with Detached Criteria (because I like to construct the detached criteria without a session)

DetachedCriteria maxQuery = DetachedCriteria.forClass(Foo.class)
    .setProjection( Projections.max("id") );
DetachedCriteria recordQuery = DetachedCriteria.forClass(Foo.class)
    .add(Property.forName("id").eq(maxId) );
懵少女 2024-10-03 16:22:43

对于hibernate中的max()函数:

criteria.setProjection(Projections.max("e.encounterId"));

For the max() function in hibernate:

criteria.setProjection(Projections.max("e.encounterId"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文