Pageable sorting not working for Spring Data JPA when using named queries - sorting

I got to grips with using Spring Data JPA however I stumbled upon an issue, searched all the net but still didn't find an answer. I got the repository working and even the paging and sorting. However, it seems that when I do the same, but specifying a named query in the #Query annotation, rather than letting Spring generate the query at runtime, the sortable part of the Pageable object is completely ignored. I can confirm this as the query generated by Hibernate does not have an "ORDER BY" clause in the latter case.
public interface TransactionRepository extends JpaRepository<Transaction, Long>
{
#Query(name = "Transaction.findParentTransactionsByStatus", countName = "Transaction.findCountParentTransactionsByStatus")
public Page<Transaction> findParentTransactionsByStatus(#Param(value = "status") TransactionStatus status, Pageable pageable);
Any ideas?

Can you post the actual HQL from your named query Transaction.findParentTransactionsByStatus?
The reason I am asking is, I encountered this same issue and it was because I had an extra end parenthesis ")" in my HQL. For some reason, it was being accepted as a valid HQL, but when passing the sort via Pageable, it was not including the sort column. My solution was to remove that extra parenthesis and it worked

Related

Spring data jpa avoid in memory pagination and n+1 using specification

I am trying to avoid in-memory pagination and N+1 while using Spring Data JPA Specification.
To be specific, I'm using the below method provided by the framework.
Page<T> findAll(#Nullable Specification<T> spec, Pageable pageable);
I tried to avoid N+1 by using #EntityGraph on the method (don't know if it's good or not) and after some research, I still don't know how to work around the in-memory pagination.
The database I'm using is Postgres if it matters
Are there any solutions to this problem?
The problem is that as soon as you fetch some kind of *-to-many association, Hibernate will do in-memory pagination, so #EntityGraph won't help. What you need is a special query that does pagination on the main/root entity and fetches associations in a second query.
I think this is a perfect use case for Blaze-Persistence Entity Views.
I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.
A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:
#EntityView(User.class)
public interface UserDto {
#IdMapping
Long getId();
String getName();
Set<RoleDto> getRoles();
#EntityView(Role.class)
interface RoleDto {
#IdMapping
Long getId();
String getName();
}
}
Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
UserDto a = entityViewManager.find(entityManager, UserDto.class, id);
The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
Page<UserDto> findAll(Specification spec, Pageable pageable);
The best part is, it will only fetch the state that is actually necessary!
But you can even use it with plain entities if you like in which case this will also run more efficient queries as you can read about in the documentation: https://persistence.blazebit.com/documentation/core/manual/en_US/index.html#pagination

Springboot JPA #Query Rest Giving PersistentEntity must not be null

I am trying to put together a simple rest service with springboot 1.4.3. I have it up and running with simple queries like findByRecid, however when I try to do a #Query statement on that same entity, I get the below error message
{"cause":null,"message":"PersistentEntity must not be null!"}
Further, if I use a fully qualified name for the entity in the query, Intellij tells me that the class isn't an entity, even though it's marked with #Entity and works with the standard springboot queries. Please assist if possible - I've been trying to figure this one out for days. Below is the query for your reference
#Query("SELECT new com.test.domain.ReceivableBeans.RecAgeBucketGroupAmountSum(r.agebucket, sum(r.amount)) from com.test.domain.Receivable as r GROUP BY r.agebucket")
List<com.test.domain.ReceivableBeans.RecAgeBucketGroupAmountSum> recByAgeBucket();
Try:
#Query("select new ReceivableStats(r.agebucket, sum(r.amount)) from Receivable r group by r.agebucket")
List< ReceivableStats> recByAgeBucket();
or name your aliases in the query, e.g.
sum(r.amount) as amount
and have your method return an Object[].

Is there a way to use UPDATE query with dynamic attributes in Spring Framework?

I'm developing a REST server application using Spring Boot.
Just got a question while constructing an UPDATE query.
Currently my UPDATE query in UserRepository is like this;
#Modifying
#Transactional
#Query(value ="update User u set u.user_dob=:userDOB, u.user_lastname=:userLastName, u.user_firstname=:userFirstname, u.user_streetaddress=:userStreetAddress where d.driver_id=:driverId", nativeQuery = true)
void updateUser(#Param("userDOB") String userDOB, #Param("userLastName") String userLastName, #Param("userFirstName") String userFirstName, #Param("userStreetAddress") String userStreetAddress);
However, I don't like to list all the attributes of User in one UPDATE query.
Is there anyway to construct UPDATE query dynamically?
For example;
Update with
set u.user_dob=:userDOB, u.user_lastname=:userLastName, u.user_firstname=:userFirstname, u.user_streetaddress=:userStreetAddress
or
u.user_lastname=:userLastName, u.user_firstname=:userFirstname
using one update method.
If you are using Spring Data JPA (seems you do), your repository interface is probably extending JpaRepository interface.
In this case, you could simply use save method.
Here are some good examples:
http://www.springbyexample.org/examples/spring-data-jpa-repository.html
http://www.springbyexample.org/examples/spring-data-jpa-code-example.html

How to limit the results of a Spring Repository with custom query

I am using a Spring repository to query a database, but because of the nature of my application I need to use a custom #Query in order to JOIN FETCH lazy collections.
This process works fine, but now I need to limit the result to a single record. I understand that Spring has the notion of findFirst or findTop1 in the method names, but this does not appear to work when you have a custom query.
How can I use a custom query and limit the result to 1 record when using a Spring repository?
you need to pass a Pageable param in your query method
#Query("select e from Entity e LEFT JOIN FETCH e.list")
public Page<Entity> find(Pageable pageable);
and call the method passing the object
repository.find(new PageRequest(0, 1));

preventing OpenJPA N+1 select performance problem on maps

When I have an entity that contains a Map, e.g.
#Entity
public class TestEntity {
#ElementCollection(fetch = FetchType.EAGER)
Map<String, String> strings = new HashMap<String, String>();
}
and I select multiple entities (SELECT z FROM TestEntity z), OpenJPA 2.0 performs one query for each TestEntity to fetch the map, even though I used FetchType.EAGER. This also happens when the Map value is an entity and I use #OneToMany instead of #ElementCollection. In principle this can be done more efficiently with one query that selects all the map entries for all returned TestEntities. For Collection-valued fields OpenJPA already does this by default (openjpa.jdbc.EagerFetchMode" value="parallel") but it seems to fail on this simple entity. (Same problem with value="join").
Could I be doing something wrong? Is there an easy way to tell OpenJPA to not perform a query per entity but only one?
Or is there already any work planned on improving this (I filed it under https://issues.apache.org/jira/browse/OPENJPA-1920)?
It is a problem for us because we wish to fetch (and detach) a list of about 1900 products which takes almost 15 seconds with OpenJPA. It takes less than a second with my own native query.
Having to write only one native query wouldn't be much of a problem but the map we use is inside a reusable StringI18N entity which is referenced from several different entities (and can be deep in the object graph), so native queries are a maintenance headache.
Any help getting performance up is greatly appreciated.
EDIT: explicitly using JOIN FETCH does not help either:
"SELECT z FROM TestEntity z JOIN FETCH z.strings"
OpenJPA's TRACE still shows that it executes one SQL statement for each individual TestEntity.
It might be a pain (correction: I know it'll be a pain) but have you tried actually mapping your 2-field TestEntity as a full JPA-persisted #Entity?
I know that Hibernate used to treat #ElementCollections rather differently to #OneToManys for example - OpenJPA could well be doing something similar.

Resources