Spring Hibernate findAll. Select only Parent class - spring

I am having a problem. I have a oneToMany relationship. I need to have findAll methods where :
a) i can select every parent with child
b) i can select ONLY parent.
I am a little confused with lazy loading etc. How can hibernate understand what i am asking for?
Thanks in advance.

Lazy Loading can be configurable, means you configure, whether you need it or not, in case of lazy loading your data will be picked when you request for it, all the data is not handPicked at FindAll at once.
I think this link is well explanatory

Related

Do I need to save both entities when adding a oneToMany relationship?

TL;DR: Is it enough to call repository.save() on the owning entity to persist the relationship or do I need to save both entities?
Let's say I have two entities, A and B and a oneToMany relationship between them. A can have multiple B's, B can have an A. B is the owning side of the relationship (has the foreign key). If I have two, already persisted entities and want to add and persist a relationship between them, then I typically do this:
a.addB(b);
b.setA(a);
bRepository.save(b);
My question is, do I also need to call aRepository.save(a)? Thanks in advance, Googling didn't help me to find the answer.
If as you describe the relationship is owned by B, A didn't change at all as far as JPA is concerned. So it doesn't need to get persisted.
If you have persisted or loaded A and B in the current session, no save at all is technically necessary. JPA keeps track of the entities, note that they are changed and will flush the changes to the database at the end of the transaction.
Good question and assuming that you have already saved the A entity the answer should be that you do NOT need to save the parent A entity again since you have added the child entity B to A's list of children yourself and A is already persisted.
If you ever reload A and all its children you should get the same list as you currently have.
Since it is lazy loaded your query should specifically load the children in the case you want that otherwise you might get into the situation where you assume that A has all its children but you doesn't if you reloaded A from the database without getting them.
In general though I have to question why you are keeping A around in the first place. Caching can be a good thing but your cache should refresh A when its children are updated and should fetch all of A's children if that is what is needed. In that case you don't need to add the new child to A yourself b/c it will be overwritten anyway. Probably doesn't hurt, but why do you want to second guess the cache?
More generally the pattern is simply to save B and be done with it. If your code needs A and all its children it should fetch from the database when needed.
These thoughts do not include JPAs entity cache since I have not attempted to get into very specific detail about that.

How to refresh Spring JPA when data is updated from querydsl directly?

I'm using spring data jpa and querydsl. I don't want to update directly through JPA because I have to submit a complete entity, which introduces an unnecessary query. So, I use querydsl instead:
val qRecord = QCoupon.coupon
jpaQueryFactory.update(qRecord)
.set(qRecord.useState, Coupon.STATE_ORDERED)
.set(qRecord.useTime, useTime)
.where(qRecord.id.eq(recordId))
.execute()
But the query after that in the same transcation cannot get the latest data, I think it has something to do with the first-level cache.
Adding #Modifying doesn't work because I didn't use #Query, the first annotation will be ignored.
I know EntityManager.clear() can fix that. But it looks too heavy, I'm not sure this is a good idea.
This post explained the cause of the problem very well but not my case -- I have rejected both two answers.
#Modifying is ignored.
EntityManager.clear() looks too heavy, and find() also need an entity.
Thanks #Jan-WillemGmeligMeyling 's idea. Because he didn't reply to me, I wrote it in my answer.
Have you tried refreshing the entity?
entityManager.refresh(entityManager.find(Coupon.class, recordId))
em.find() will not look up the entire table, that's what I want.

Querying multiple tables using jpa repository

Suppose if I have 3 entities - User, Skills, Department
and I have repositories corresponding to all of them - UserRepository, SkillRepository, DepartmentRepository.
I understand that the relation mapping between entities i.e. one-one many-many should be specified in the respective entity classes. The question is I want to use all of the 3 entities in a query. How would I do it? A single repository is associated with only one entity right? So, how/where would I write it?
As there are many different ways to specify queries with Spring Data JPA there are various answers to this.
Maybe you don't have to. If entity A references B and you just want to get the Bs with your A you simply use your ARepository to load As and use object navigation to get your Bs. You might read up on eager and lazy loading for more information about how to control this.
If you want referenced entities in the where condition you can use property paths in your query method names: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions
If you are using #Query annotations you can do (almost) whatever you want with JPQL. Among others, you may as well navigate properties to use them in where clauses.
In general, you'd put that query in the matching repository based on the primary entity returned.

Spring JPA custom query with combination of parameters in WHERE condition?

How to write JPA query in Spring Data that uses at least one of three parameters?
I have these three parameters:
Id (PK)
Name
Surname
Client must supply at least one of these three parameters and I want to find user by these not-empty parameters.
Is it possible to create such custom query to my repository or do I have to create custom queries for all possible combination of WHERE conditions?
You can have your repository extend org.springframework.data.querydsl.QueryDslPredicateExecutor and use the inherited findAll(Predicate predicate) method to query using any combination of parameters.
You would not then have to write any query methods:
http://docs.spring.io/spring-data/jpa/docs/1.10.5.RELEASE/reference/html/#core.extensions.querydsl
You can also have the Predicate automatically bound in a Spring MVC Controller as detailed here:
https://spring.io/blog/2015/09/04/what-s-new-in-spring-data-release-gosling#querydsl-web-support
and here:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web.type-safe
So your controller can then automatically handle a search with 1,2 or all 3 parameters passed as request parameters without your having to write any code at all.
This is where you need the ability to create dynamic queries at runtime.
In your application code, you should have logic to build the predicate based on whether each of the above properties from the input DTO is empty or not.
One way to do it is to use QueryDSL.
To use QueryDSL, you should include the relevant dependency in your pom/gradle file and then your repository should extend the QueryDslPredicateExecutor interface. This will give you two additional generic finder methods.
T findAll(Predicate) or
Page<T> findAll(Predicate, Pageable)
One thing to keep in mind is that the above two methods are appropriate where this is no need to do a join
Your requirement here seems to be a single table query, so either one of the finder methods should suffice.
If you do need to do a join with other tables and need fine grained control over how the JOIN happens (INNER JOIN vs LEFT OUTER JOIN vs CROSS JOIN) etc, then you should consider creating a Custom repository that your repository can extend.
And then provide your own customImpl that you can now access from the repository.
thanks a lot for the reply ... as i read Spring is not easy flexible as other framework... for i.e i tried some node js api framework and it is easier and more flexible .. what do you think about this ?

Spring Data NEO4J: relations have null values

I have a spring 3.1 (Milestone) and Spring Data Neo4J 2.1 RC project running set up. All starts up properly and the neo4j database is being populated as desired, also visible in neoclipse.
Now I fetch an entity (lets call it Container.java) by id and have the relation "Event".
The relation in Container.java is modelled as follows:
#RelatedTo(type="HAS_EVENTS", direction = Direction.BOTH)
Set<Event> events = new HashSet<Event>();
When I access container.getEvents() and iterate over them, I can see that the single event has an id, but all other properties are null :(
When having a look with neoclipse, all properties are saved as they should be.
Is there some kind of "eager" or "lazy" loading? I do not use a #RelationshipType.
One night spent: I have to add the #Fetch entity. Makes sense from my point of view, as if there was eagerly loading enabled, I could easily generate cycles :)
#Fetch entity is for eager loading
for lazy loading ,you can use neo4jTemplate.fetch method template.fetch(Event.getEvents())

Resources