LIMIT clause is not working in JPA Named Queries


#1

Hii,

I am using JPA with Hibernate

<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-entitymanager</artifactId>
	<version>4.3.6.Final</version>
	<exclusions>
		<exclusion>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.1-api</artifactId>
		</exclusion>
	</exclusions>
</dependency>

<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-entitymanager</artifactId>
	<version>4.3.6.Final</version>
</dependency>

<dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>javax.persistence</artifactId>
	<version>2.1.0</version>
</dependency>

I am trying to write a Named Queries in JPA with LIMIT:

@NamedQuery(name="Getuser.findAlldfdf", query="SELECT g FROM Getuser g LIMIT 10,20")

And I get this error:

The abstract schema type 'LIMIT' is unknown.
An identification variable must be provided for a range variable declaration.
The identification variable '10' is not following the rules for a Java identifier.
The FROM clause has 'Getuser g' and 'LIMIT 10' that are not separated by a comma.

Please help me to add LIMIT condition to my query.


#2

That’s not how you do pagination. LIMIT is a MySQL and PostgreSQL specific only.

Use the javax.persistence.Query setMaxResults and setFirstResults instead:

Query query = email.getNamedQuery("Getuser.findAlldfdf");
query.setMaxResults(10);
query.setFirstResult(1);

Check out this article for more details.