In Hibernate 3, is there a way to do the equivalent of the following MySQL limit in HQL?
select * from a_table order by a_table_column desc limit 0, 20;
I don't want to use setMaxResults if possible. This definitely was possible in the older version of Hibernate/HQL, but it seems to have disappeared.
This was posted on the Hibernate forum a few years back when asked about why this worked in Hibernate 2 but not in Hibernate 3:
Limit was never a supported clause
in HQL. You are meant to use
setMaxResults().
So if it worked in Hibernate 2, it seems that was by coincidence, rather than by design. I think this was because the Hibernate 2 HQL parser would replace the bits of the query that it recognised as HQL, and leave the rest as it was, so you could sneak in some native SQL. Hibernate 3, however, has a proper AST HQL Parser, and it's a lot less forgiving.
I think Query.setMaxResults() really is your only option.
// SQL: SELECT * FROM table LIMIT start, maxRows;
Query q = session.createQuery("FROM table");
q.setFirstResult(start);
q.setMaxResults(maxRows);
If you don't want to use setMaxResults() on the Query object then you could always revert back to using normal SQL.
The setFirstResult and setMaxResults Query methods
For a JPA and Hibernate Query, the setFirstResult method is the equivalent of OFFSET, and the setMaxResults method is the equivalent of LIMIT:
List<Post> posts = entityManager.createQuery("""
select p
from Post p
order by p.createdOn
""")
.setFirstResult(10)
.setMaxResults(10)
.getResultList();
The LimitHandler abstraction
The Hibernate LimitHandler defines the database-specific pagination logic, and as illustrated by the following diagram, Hibernate supports many database-specific pagination options:
Now, depending on the underlying relational database system you are using, the above JPQL query will use the proper pagination syntax.
MySQL
SELECT p.id AS id1_0_,
p.created_on AS created_2_0_,
p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?, ?
PostgreSQL
SELECT p.id AS id1_0_,
p.created_on AS created_2_0_,
p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?
SQL Server
SELECT p.id AS id1_0_,
p.created_on AS created_on2_0_,
p.title AS title3_0_
FROM post p
ORDER BY p.created_on
OFFSET ? ROWS
FETCH NEXT ? ROWS ONLY
Oracle
SELECT *
FROM (
SELECT
row_.*, rownum rownum_
FROM (
SELECT
p.id AS id1_0_,
p.created_on AS created_on2_0_,
p.title AS title3_0_
FROM post p
ORDER BY p.created_on
) row_
WHERE rownum <= ?
)
WHERE rownum_ > ?
The advantage of using setFirstResult and setMaxResults is that Hibernate can generate the database-specific pagination syntax for any supported relational databases.
And, you are not limited to JPQL queries only. You can use the setFirstResult and setMaxResults method seven for native SQL queries.
Native SQL queries
You don't have to hardcode the database-specific pagination when using native SQL queries. Hibernate can add that to your queries.
So, if you're executing this SQL query on PostgreSQL:
List<Tuple> posts = entityManager.createNativeQuery(
SELECT
p.id AS id,
p.title AS title
from post p
ORDER BY p.created_on
""", Tuple.class)
.setFirstResult(10)
.setMaxResults(10)
.getResultList();
Hibernate will transform it as follows:
SELECT p.id AS id,
p.title AS title
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?
Cool, right?
Beyond SQL-based pagination
Pagination is good when you can index the filtering and sorting criteria. If your pagination requirements imply dynamic filtering, it's a much better approach to use an inverted-index solution, like ElasticSearch.
If you don't want to use setMaxResults, you can also use Query.scroll instead of list, and fetch the rows you desire. Useful for paging for instance.
You can easily use pagination for this.
#QueryHints({ #QueryHint(name = "org.hibernate.cacheable", value = "true") })
#Query("select * from a_table order by a_table_column desc")
List<String> getStringValue(Pageable pageable);
you have to pass new PageRequest(0, 1)to fetch records and from the list fetch the first record.
You need to write a native query, refer this.
#Query(value =
"SELECT * FROM user_metric UM WHERE UM.user_id = :userId AND UM.metric_id = :metricId LIMIT :limit", nativeQuery = true)
List<UserMetricValue> findTopNByUserIdAndMetricId(
#Param("userId") String userId, #Param("metricId") Long metricId,
#Param("limit") int limit);
String hql = "select userName from AccountInfo order by points desc 5";
This worked for me without using setmaxResults();
Just provide the max value in the last (in this case 5) without using the keyword limit.
:P
My observation is that even you have limit in the HQL (hibernate 3.x), it will be either causing parsing error or just ignored. (if you have order by + desc/asc before limit, it will be ignored, if you don't have desc/asc before limit, it will cause parsing error)
If can manage a limit in this mode
public List<ExampleModel> listExampleModel() {
return listExampleModel(null, null);
}
public List<ExampleModel> listExampleModel(Integer first, Integer count) {
Query tmp = getSession().createQuery("from ExampleModel");
if (first != null)
tmp.setFirstResult(first);
if (count != null)
tmp.setMaxResults(count);
return (List<ExampleModel>)tmp.list();
}
This is a really simple code to handle a limit or a list.
Criteria criteria=curdSession.createCriteria(DTOCLASS.class).addOrder(Order.desc("feild_name"));
criteria.setMaxResults(3);
List<DTOCLASS> users = (List<DTOCLASS>) criteria.list();
for (DTOCLASS user : users) {
System.out.println(user.getStart());
}
Below snippet is used to perform limit query using HQL.
Query query = session.createQuery("....");
query.setFirstResult(startPosition);
query.setMaxResults(maxRows);
You can get demo application at this link.
You can use below query
NativeQuery<Object[]> query = session.createNativeQuery("select * from employee limit ?");
query.setparameter(1,1);
#Query(nativeQuery = true,
value = "select from otp u where u.email =:email order by u.dateTime desc limit 1")
public List<otp> findOtp(#Param("email") String email);
i have an SQL like:
Query 1:
SELECT
t.name,
sum(t.value)
FROM
myTable t
WHERE
-- conditions...
GROUP BY
t.name
HAVING sum(t.value) >= 100
and i have:
Query 2:
select count(*) from (
-- QUERY1
) as countQuery
And i'm trying to do it on QueryDSL.
I already have my Query 1 as an JPAQuery.
Now a need to use it as a subquery, so i'm trying to do something like:
JPASubQuery subQuery = new JPASubQuery(query1.getMetadata());
new JPAQuery().from(subquery).count();
But it's not possible to add a SubQuery in the FROM clause.
It would be a nice feature.
Ok, it's not possible due to JPA limitations:
https://github.com/querydsl/querydsl/issues/1471
Excuse me for anking again about this issue but I need to have a JPA query for this:
select username, count(*)
from Records
group by username
order by count(*) desc
limit 1
I thought about smth like:
select r.username,count(*) from Records r order by r.username desc
and then to call
getResultList().get(0)
but I am allowed to write only:
select r from Records r order by r.username desc
and in this case I do not know how to get what I need.
Does anyone have any idea?
The SQL query has a group by, and orders by count. The JPA query doesn't have any group by and orders by user name. So I don't see how they could return the same thing.
The equivalent JPQL query is
select r.username, count(r.id)
from Record r
group by r.username
order by count(r.id) desc
If you call setMaxResults(1) on the Query object, the limit clause will be added to the generated SQL query, making it completely equivalent.
I would like to execute this SQL request in QueryDSL JPA
SELECT authorizationitem.*
FROM authorizationitem
INNER JOIN
(
SELECT `authorize`
FROM authorizationitem
GROUP BY `authorize`
HAVING COUNT(*)>1
) a2
ON authorizationitem.`authorize` = a2.`authorize`;
in order to find duplicated row in a table, i should execute this request. But with QueryDSL, i cannot find the way to write this.
It seems QueryDSL does not allow subQuery in Inner Join :s
Any suggestion?
Thanks
regards,
You can't express this with HQL/JPQL, so you will need to expess this with SQL. Querydsl JPA provides the possibility to express both JPQL and SQL queries through its API.
You can try using a subquery in the WHERE clause, but it will probably be less efficient than the subquery in the FROM clause. Make sure there is an index on authorizationitem.authorize to optimize the joins and the GROUP BY.
SELECT authorizationitem.*
FROM authorizationitem
WHERE EXISTS (
SELECT `authorize`
FROM authorizationitem2
WHERE authorizationitem2.authorize = authorizationitem.authorize
GROUP BY `authorize`
HAVING COUNT(*)>1
);
or
SELECT authorizationitem.*
FROM authorizationitem
WHERE (
SELECT count(*)
FROM authorizationitem2
WHERE authorizationitem2.authorize = authorizationitem.authorize
GROUP BY `authorize`
) > 1;
I have a problem in creating subqueries with Hibernate. Unfortunately the Subqueries class is almost entirely undocumented, so I have absolutely no clue how to convert the following SQL into a Hibernate Criteria:
SELECT id
FROM car_parts
WHERE car_id IN ( SELECT id FROM cars WHERE owner_id = 123 )
I was hoping the following would 'just work':
session.createCriteria(CarParts.class).add(eq("car.owner", myCarOwner));
but unfortunately it does not. So it seems I actually have to use the Subqueries class to create the Criteria. But I was unable to find a reasonable example though Google, so that leads me to asking it here.
Try Like this:
Table details): Category (id, name, desc, parentId, active)
DetachedCriteria subCriteria = DetachedCriteria
.forClass(Category.class);
subCriteria.add(Restrictions.isNull("parent"));
subCriteria.add(Restrictions.eq("active", Boolean.TRUE));
subCriteria.add(Restrictions.eq("name", categoryName));
subCriteria.setProjection(Projections.property("id"));
Criteria criteria = getSession().createCriteria(Category.class);
criteria.add(Restrictions.eq("active", Boolean.TRUE));
criteria.add(Subqueries.propertyEq("parent", subCriteria));
It will generate the query like:
select
*
from
Categories this_
where
this_.active=1
and this_.parentId = (
select
this0__.id as y0_
from
Categories this0__
where
this0__.parentId is null
and this0__.active=1
and this0__.name='Health Plan'
)
Good Luck!
-Rohtash Singh
Try to create an alias for the "car" property before adding the eq expression like this:
session.createCriteria(CarParts.class)
.createAlias("car", "c")
.add(eq("c.owner", myCarOwner));
As first check the ORM configuration between Car and CarPart entities, usually you need the setup the relationship between them. After that try to execute the following code:
List result = session.createQuery("from " + CarPart.class.getName() +
" as parts join parts.car as car where car.owner = :myOwner")
.setParameter("myOwner", 123)
.list();