How to fixe lines' s result of a query with JQL language - jpa

I wanna to know How to fixe lines' s result of a query with JQL language , like "LIMIT" in SQL ?

With JPA, you do not specify this in the query string, but on a Query object you create from your query string, using setMaxResults:
TypedQuery<Student> query = em.createQuery("select s from Student s", Student.class);
query.setMaxResults(30);
List<Student> first30Students = query.getResultList();

Related

Count in Spring Data JPQL join query throwing IllegalArgumentException

I have a query using JPQL in the annotation #Query in Spring Data which looks like below
#Query(value = "select distinct a from EntityA as a left join fetch a.listEntityB as b where ...")
public List<EntityA > find....(#Param("") String value, Pageable pageable);
Now I need to know the total number of records of the query. As Pageable is giving me partial list, I am writing another count query without the Pageable. My count query looks like below:
#Query(value = "select count(distinct a) from EntityA as a left join fetch a.listEntityB as b where ...)
public long count...(#Param("") String value);
However, I am getting "IllegalArgumentException: Validation failed for query" error from this query to count the records. When I change the count query to "select count(distinct a) from EntityA" , it works fine. I am not sure what is the problem when I use the join. I did not get any helpful documents so far. Is there any better solution to get the total number of records for the Pageable query.
Put the CountQuery in the same annotation as the query itself. So
#Query(value = "select ...", countQuery = "select count..")
public List<EntityA > find....(#Param("") String value, Pageable pageable);
Also remove the "fetch" from the countQuery.
To get the total records, you can just reference the page.getTotalElements() to return the total number of records.

How to fetch records using JPQL with case insensitive match

I am trying to fetch the records of employees using JPQL but I don't know name with exact case.
select e from Employee e where e.name = 'rahul'
what changes I need to make in above JPQL to get the list of employee whose name is Rahul, rahul or RAHUL etc.
I got a way to fetch the records, though not sure if this is efficient one or not.
TypedQuery<Employee> query = em.createQuery("select e from Employee e where lower(e.name) = :name", Employee.class);
query.setParameter("name", name.toLowerCase());
query.getResultList();

Criteriabuilder like, how to do it for Long?

i try use "like" method from Criteriabuilder for get all record based on pattern " 10% ".
I want get record where ID is - 101, 10002, 1003,1000 etc...
I've use this code:
Predicate p = cb.like(r.<String>get("ID").as(String.class), "10%")
but i got Exception where i see what postgres can't execute query like this:
SELECT ID, NAME, SOMETHING FROM TABLE WHERE ID LIKE 10%
That is JPA (Glassfish 4.x) generate wrond query.
Right query must like that :
SELECT ID, NAME, SOMETHING FROM TABLE WHERE CAST (ID as TEXT) LIKE '10%'
How to build query via Criteria API that i got a right query for postgres ?
Updated:
I try write a CAST function :
Expression<String> postgresqlCastFunction = cb.function("CAST", String.class, r.<String>get("ID").as(String.class));
Predicate p = cb.like(postgresqlCastFunction, "10%");
but got a query like this :
FROM TABLE WHERE (CAST(ID) LIKE ?)
, so, how to add need expression in function for this right result -
FROM TABLE WHERE (CAST(ID as TEXT) LIKE ?) ..
An example implementation using PostgreSQL native TO_CHAR function may look as follows:
JPQL
SELECT r FROM Records r
WHERE FUNCTION('TO_CHAR', r.ID, 'FM9999999999') LIKE :pattern
Criteria API
Path<String> id = r.get("ID");
Expression<String> format = cb.literal("FM9999999999");
Expression<String> function= cb.function("TO_CHAR", String.class, id, format);
ParameterExpression<String> pattern = cb.parameter(String.class, "pattern");
Predicate like = cb.like(function, pattern);
cq.where(like);
also you can build the query as an one-liner:
cq.where(cb.like(cb.function("TO_CHAR", String.class, r.get("ID"), cb.literal("FM9999999999")), cb.parameter(String.class, "pattern")));
Execute the above query:
Query q = em.createQuery(cq).setParameter("pattern", "10%");

Get count from query

I am using mysql 5.5 with openjpa 2.3.0.
I have entities with namedQueries (generated in netbeans - I would like to be able to use this), for example:
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
#NamedQuery(name = "User.findByGender", query = "SELECT u FROM User u WHERE u.gender = :gender")
I am creating restfull aplication with paged results. I would like to return for every paged result the Content-Range header as 1-20/250 where 20 is pagesize, 250 total count.
I tried to create a query
entityManager.createNativeQuery("SELECT count(1) FROM (" + namedQuery.toString() + ") as foo;");
where I could dynamicaly insert any named query and return the count without returning the result list -> it should be faster.
When I execute this, exception occurs
SQL state 42S22: Unknown column 'u' in 'field list'
Executing the query itself in entitymanager is ok.
Can I use the entity manager or criteria builder to create a query for counting results without returning the result list (and without writing for every namedQuery a count duplicate)? thank you for helping.
You are mixing JPQL with native queries. JPQL says SELECT u FROM entity u, SQL would be SELECT * FROM entity u or SELECT col1,col2,col3 FROM entity u
You could write a JPQL named query counting the stuff, e.g. SELECT COUNT(u) FROM entity u. A getSingleResult() would then return an Object[], whose first element contains the count.
Not nice but working. Why do You have to query for the number anyway? Pagination means next = lastindex+pagesize. if next < lastindex+pagesize, the end is reached.

Wildcard not working? - JPQL in JPA

I've got a class MovieElement, a field url which is the id, and an other field name.
Just for testing the values of name and url are the same.
An object is persisted with name & url = "www.test.com"
But I cannot get the wildcard working, I tried a query like:
query = em.createQuery("SELECT m FROM MovieElement m WHERE m.name LIKE :keyword");
query.setParameter("keyword", "%test%");
query.getResultList();
This gives an empty result.
But the following works:
query = em.createQuery("SELECT m FROM MovieElement m WHERE m.name LIKE :keyword");
query.setParameter("keyword", "www.test.com");
query.getResultList();
Evenso all the next ones results in a null:
MovieElement el = em.find(MovieElement.class, "%test%");
query = em.createQuery("SELECT m FROM MovieElement m WHERE m.name LIKE :keyword");
query.setParameter("keyword", "www.test.co_");
query.getResultList();
query = em.createQuery("SELECT m FROM MovieElement m WHERE m.name LIKE :keyword");
query.setParameter("keyword", "%");
query.getResultList();
Due to the last query it seems the code doesn't take the wildcard into account.
Further I'm using DataNucleus and MongoDb.
Anyone an idea? Thx!
Found the solution: Seems like Datanucleus for mongodb recognizes ".*" as the wildcard instead of "%"