简体   繁体   中英

Hibernate get project last version from database

I'm new to hibernate framework and I don't know how to write code using hibernate functions to get needed object. In internet I have seen code using criteria and projection, but the query for projection is not what i need. For example i need to get last version of project by date. This is criteria

Criteria criteria = session
                    .createCriteria(Assembly.class)
                    .setProjection(Projections.max("date"));

-First problem is that it gets max value from all table(don't know how to set for searching only exact project name date). -Second problem that it returns date but i need object of class. In summary i need from hibernate to generate such query: SELECT * FROM assembly WHERE projectName = ? AND .. SELECT * FROM assembly WHERE projectName = ? AND .. .don't know how to finish it, date = max() - won't work as I understand. One of the bad solution is to get all exact projects and then compare there dates, but I think there's gonna be good solution.

This should work

Assembly newest = 
    (Assembly) session.createCriteria(Assembly.class)
    .add(Restrictions.eq("projectName", projectName))
    .addOrder(Order.desc("date"))
    .setMaxResults(1)
    .uniqueResult();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM