Get native SQL from QueryDSL JPA (JPAQuery or JPQLQuery) - jpa

I have a requirement to count the number of group by records for pagination purpose. For example:
select count(*) from (
select name, count(id) from customer
group by name
);
However it couldn't be achieved via QueryDSL due to the limitation of JPA
where JPQL doesn't allows to select count from sub query.
Is it possible to get the native SQL from QueryDSL JPAQuery or JPQLQuery? My plan is to construct and execute the select count native SQL statement via EntityManager.
String subQueryNativeSQL = "..."; // native SQL from QueryDSL
Query q = em.createNativeQuery("select count(*) from (" + subQueryNativeSQL + ")");
long count = (long) q.getSingleResult();

Both JPAQuery and JPQLQuery implement Projectable interface and implement count() method - and you ain't need subqueries

Related

How to combine and/or condition in jpql spring

I'm trying to execute the below query with #Query annotation
select * from table where ((entity=1 and entityId=:userId) or (entity=0 and entityId=:productId)) and group=:group
, but the spring JPQL converts the query to
select * from table where (entity=1 and entityId=:userId or entity=0 and entityId=:productId) and group=:group
any solution to above this conversion?

How to add oracle hint (use_nl) to a spring boot jpa query

I have a hql query
select new com.packagename.CountryInfoDto(c.countriesId, c.internationalCode, c.countryName, ot.name) from Country c
inner join OtherTable ot on c.otid = ot.id
where c.deleted = (:deleted)
order by c.countryName
I create the query like this.
TypedQuery query = entityManager.createQuery(queryString,
BookingInfoDto.class);
Now if I want to hint use_nl(c ot) (use nested loops) how can I add that hint?
You can't. You need to use a native query.

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 call spring jap query none parameters

I use spring data jpa with native query
I have already some query like this
How to use native query none parameter.
String q="SELECT t1.blockNumber-1 FROM someTAble t1 LEFT JOIN someTAble t2 ON t2.blockNumber = t1.blockNumber-1 WHERE t2.blockNumber IS NULL AND t1.blockNumber> 0 ORDER BY t1.blockNumber";
#Query(value = q,nativeQuery = true)
List<Entity> findByBlockNumberIs();
they are occur errors Column 'sequence' not found.
That query means are when i insert some Contiguous data int value then i find missing data.
But
this query working
SELECT *,t1.blockNumber-1 FROM someTAble t1 LEFT JOIN someTAble t2 ON t2.blockNumber = t1.blockNumber-1 WHERE t2.blockNumber IS NULL AND t1.blockNumber> 0 ORDER BY t1.blockNumber
The difference between the two queries is whether there is a '*' or not
how to change simple to my query.
How to i changed error
OR How to use spring data jpa predicate
QEntity qBe1= QEntity .blockEntity;
QEntity qBe2= QEntity .blockEntity;
build.and(qBe2.blockNumber.eq(be.getBlockNumber()-1))
.and(qBe2.blockNumber.isNull().and(qBe1.blockNumber.gt(0)));
is predicate can use left join?
well...
use this.
List<Integer> findByBlockNumber()

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.