Spring Hibernate : Multiple resultset mapping - spring

I want to understand the limitations of Spring's Data repository.
While querying the database, it seems that Spring repository can only return entities, or a collection of same type, like string/int etc. It makes sense because the Spring Repository is a function and a function can only return one result.
So what if I need to execute a complexe sql by using #Query annotation, and expect more than one result? like a collection of entityies and a number.
I don't think it is possible with Spring Repository, so if i'm wrong, please correct me.
And more importantly, how could I do that by using spring?

No, it's not possible that I know of for the Repository to work with queries, but the Repository is used by a Spring ServiceImpl anyway and you can Inject an EntityManager into the serviceImpl and use that. For example see Getting started with Spring Data JPA:
#PersistenceContext
private EntityManager em;
TypedQuery query = em.createQuery("select a from Account a where a.customer = ?1", Account.class);
query.setParameter(1, customer);
return query.getResultList();

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

Spring Data JPA + Bytecode Enhancement

Is it possible to load #*ToOne attributes eagerly using JPA interface(Entity Graphs) which are set lazy using #LazyToOne , #LazyGroup in the parent entity class and enabled bytecode enhancement ? I am trying to load such attributes eagerly using entity graph but it is firing another query for such #*ToOne attributes when an parent entity is queried.
Trying to have another way to override static fetch type in entity classes including #LazyToOne which was added with bytecode enhancement.
Using Spring 5.1.3 , Spring JPA 2.2 , Hibernate 5.4.19
Update : Data JPA is working as expected and i could see joins for the attributes which i am trying to fetch eagerly but those lazy attributes are not being initialised with the join query response and hibernate causing each query on referencing attributes which were annotated with #LazyToOneOption.NO_PROXY and was already fetched eagerly using entity graph in my repository.
How can i avoid this second select which is not even required since i got the that data eagerly from entity graph in JPA respository ??
Any help would be highly appreciated.
Entity Graphs just like Hibernate fetch profiles apply regardless of what annotations you have on the association. If it does not, maybe there is a bug in Spring Data or maybe even Hibernate. It's probably best if you create a new JIRA issue with a test case reproducing the problem.
Having said that, I think this is the 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.
An example DTO model 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();
}
// Other mappings
}
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

Spring boot , Spring data JPA concurrent access

I am trying to create a Restful API with Spring boot and Spring data JPA to do the CRUD operations. The database will be Oracle relational database.Now for concurrent access , If we only use spring transactions using #Transactional, will that serve our purpose of concurrent CRUD operations.
I see there are JPA Optimistic and pessimistic locking strategy version column. My specific question is , for concurrent CRUD operations do we need both Spring transactions and JPA locking strategy? OR only configuring Spring transactions accordingly will be sufficient?
Try to start with the following simple approach that IMO will be suitable in many cases: Optimistic locking with Spring Retry.
1) Add version property annotated with #Version to your entities (you can do it in base abstract entity class, for example, to simplify the process):
#Entity
public class MyEntity {
#Id
#GeneratedValue
private Long id;
#Version
private Long version;
// other stuff
}
In this case when you, for example, will update your entity then Hibernate will use the current value of version property in condition clause of update query, and increment this value to store the entity with it. For example this code of some service:
#Transactional
public Optional<MyEntity> update(Long id, MyEntity source) {
return myEntityRepository
.findById(id)
.map(target -> mapper.updateEntity(source, target));
}
will generate the following SQL queries:
1. select * from my_entities where id = ?;
2. update my_entities set ..., version = <version value from query #1> + 1 where id = ? and version = <version value from query #1>;
So if another concurrent process manages to update this entity first, then your method fails with an exception (OptimisticLockException).
2) To manage to exceptions in that method, add #Retryable annotation to it (and #EnableRetry annotation on your config or application class):
#Retryable(maxAttempts = 2)
#Transactional
public Optional<MyEntity> update(Long id, MyEntity source) {
// ...
}
In this case, if an exception rises in that method it will be called again in a new transaction to repeat the operation.
Additional info:
Optimistic Locking in JPA
Guide to Spring Retry
My Spring Retry demo
Optimistic lock is default strategy of JPA. Optimistic locking is can be used for most of the applications. Optimistic lock is much more easier and efficient. Pessimistic lock need to be used in cases like, where you need to know Collision before committing your transaction.
So you do not need to configure a locking strategy.

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

JPA / JTA / #Transactional Spring annotation

I am reading the transaction management Using Spring framework. In first combination I used Spring + hiberante and used Hibernate's API's to control the transaction (Hibenate API's). Next, I wanted to test using #Transactional annotation, and it did work.
I am getting confused on:
Do JPA , JTA, Hibernate have their "own" way of transaction
management. As an example, consider if I use Spring + Hibernate, in
that case would u use "JPA" transactions?
Like we have JTA, is it true to say we can use Spring and JTA to
control transactions?
The #Transactional annotation, is that specific to Spring
Framework? From what I understood, this annotation is Spring
Framework specific. If this is correct, is #Transactional using
JPA/JTA to do the transaction control?
I do read online to clear my doubts, however something I don't get direct answer. Any inputs would be great help.
#Transactional in case of Spring->Hibernate using JPA i.e.
#Transactional Annotations should be placed around all operations that are inseparable.
So lets take example:
We have 2 model's i.e. Country and City.
Relational Mapping of Country and City model is like one Country can have multiple Cities so mapping is like,
#OneToMany(fetch = FetchType.LAZY, mappedBy="country")
private Set<City> cities;
Here Country mapped to multiple cities with fetching them Lazily.
So here comes role of #Transactinal when we retrieve Country object from database then we will get all the data of Country object but will not get Set of cities because we are fetching cities LAZILY.
//Without #Transactional
public Country getCountry(){
Country country = countryRepository.getCountry();
//After getting Country Object connection between countryRepository and database is Closed
}
When we want to access Set of Cities from country object then we will get null values in that Set because object of Set created only this Set is not initialize with there data to get values of Set we use #Transactional i.e.,
//with #Transactional
#Transactional
public Country getCountry(){
Country country = countryRepository.getCountry();
//below when we initialize cities using object country so that directly communicate with database and retrieve all cities from database this happens just because of #Transactinal
Object object = country.getCities().size();
}
So basically #Transactional is Service can make multiple call in single transaction without closing connection with end point.
Hope this will helpful to you.

Resources