The question is simple can this query be done in Hibernate using Criteria or DetachedCriteria? i guess not but i wanted to do this question maybe exist a workaround.
SELECT
COLUMNS
FROM table
WHERE id not in (
SELECT * FROM (
SELECT id
FROM table
WHERE
SOMECONDITIONS
ORDER BY timestamp desc limit 0, 15
)
as t);
I will mark the answer by @Dean Clark as correct but another question arises is the following
where can i find the findByCriteria from SessionFactory we are not using Spring
Writing query apart from the scope of Session facility is provided by the Hibernate using org.hibernate.criterion.DetachedCriteria class this class may be used in anywhere in the code. To fetch Criteria a Session may be passed in the getExecutableCriteria () method, this method is executed within a Session.
The Hibernate Session interface contains several overloaded createCriteria () methods. Pass the persistent object’s class or its entity name to the createCriteria () method, and hibernate will create a Criteria object that returns instances of the persistence object’s class when your application executes a criteria query.
-Detached criteria is very good alternate when the hibernate session is not present. -The criteria are online, which means that it uses Session class object. But the detached criteria is offline because it doesn't need a session. -Then the detach criteria allow code reusability.
Using a DetachedCriteria is exactly the same as a Criteria except you can do the initial creation and setup of your query without having access to the session. When it comes time to run your query, you must convert it to an executable query with getExecutableCriteria (session).
To exactly match you query, you really need to do it with 2 steps, but I'd avoid this if possible:
final Criteria innerCriteria = getSession().createCriteria(YourEntity.class);
// SOME CONDITIONS
innerCriteria.add(Restrictions.eq("someColumn", "someValue"));
innerCriteria.addOrder(Order.desc("timestamp"));
innerCriteria.setMaxResults(15);
innerCriteria.setProjection(Projections.id());
List<YourIdClass> ids = innerCriteria.list();
final Criteria criteria = getSession().createCriteria(YourEntity.class);
criteria.add(Restrictions.not(Restrictions.in("id", ids)));
List<YourEntity> results = criteria.list();
Would the objects you're trying to identify have the same "SOMECONDITIONS"? If so, this would functionally accomplish what you're looking for:
final DetachedCriteria criteria = DetachedCriteria.forClass(YourEntity.class);
// SOME CONDITIONS
criteria.add(Restrictions.eq("someColumn", "someValue"));
criteria.addOrder(Order.desc("timestamp"));
getHibernateTemplate().findByCriteria(criteria, 16, 9999999);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With