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

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 ?

Related

Spring JPA Derived query method groupBy

Hi I was building an app and was wondering on how I can convert this query into a derived query method without using the annotation #Query:
SELECT address, COUNT(*) address FROM `employee` GROUP BY address ORDER BY address DESC LIMIT 5
I have tried it here is how I did it
List<Employee> countByAddressGroupByAddressByOrderByAddressDescLimit5();
This throws the following error
Invalid derived query! No property groupByAddressBy found for type String! Traversed path: Employee.address.
I was wondering if what am I doing wrong here thank you in advance.
I don't think query derivation supports group by.
You can't.
Derived queries don't support GROUP BY.
Derived queries are intended only for simple queries, where the mapping between a normal method name that you might choose independently from Spring Data and the query needed for implementation is obvious.
For more complex cases like the one you describe other mechanisms are available, like annotated or named queries. Nobody wants to use a method name like countByAddressGroupByAddressByOrderByAddressDescLimit5 anyway.
As others said, derived queries do not support this. There might be other reasons besides simply not being a 'practical' solution.
AFAIK derived query methods are restricted to retrieving instances just for the entity type managed by the repository (you can retrieve MyEntity, Optional<MyEntity>, Collection<MyEntity>, etcetera) or projections that match the fields/columns used for the managed entity.
When you use 'Group By', you break with this resultset structure, you usually have to explicitly indicate which columns you want to retrieve or which operations you want to perform on the grouped columns (which would be impossible using just a method name).
TL;DR
You can't easily indicate the columns you want to include in a 'Grouped By' query result, so no, I don't think there is a way to use this technique with 'Group By'.

How to create custom SpringBoot Crud Repository Methods to find specific details?

So i have 5 tables as Users,Orders,Products,Ingredients and nutrients,
Each is connected to adjacent table via #ManyToOne annotation.
What i am stuck at is how to find product details of a particular user for a particular order and similarly finding ingredients for a particular product for a particular order for a particular user and similarly for nutrients.
I know i have to declare custom crud methods according to a given syntax and i did so but still the method is not working.
Here is the link to the git repository
https://github.com/Guneet007/API.git
You can use Specification/Querydsl for defining custom criteria. Because we should use more than 3 parameters with AND suffix.
One more issue I have found in your code is that your property name not match with your method findByProductId() it should be findByProduct(Product product). Look same for others too.
https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

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.

Same query method and parameters with different return in Spring Data

I want to use projections in order to return less elements for the same queries.
Page<Network> findByIdIn(List<Long> ids);
Page<NetworkSimple> findByIdIn(List<Long> ids);
Since the queries are created using the name of the method, what options do I have to do the same query but with different name ?
I ran into this today, and the accepted answer is actually incorrect; you can change the method name without altering the behavior. According to the Spring Data documentation:
Any text between find (or other introducing keywords) and By is considered to be descriptive unless using one of the result-limiting keywords such as a Distinct to set a distinct flag on the query to be created or Top/First to limit query results.
Thus you can have a method named findByIdIn and another named findNetworkSimpleByIdIn and the two will return the same data (optionally converted to a different form depending on the defined return type).
Spring Data query via method is constructed by convention and you can't change the name and yet expecting a same behavior.
You can try to use #Query annotations which doesn't depend on the method name, or possibly implementing custom DAO using JPAQuery plus FactoryExpression which has the same effect as projections.

How to obtain a generic search/find method with spring data?

All I need is to provide all my repositories with a generic search/find method.
Something like this:
public interface BaseRepository<T, ID extends Serializable>
extends PagingAndSortingRepository<T, ID> {
Iterable<T> search(SearchParameters sp);
}
where the SearchParameters object represents a set of values for each property, and probably a condition to apply on them.
Jpa Criteria is probably the way to go, but I'm really having a hard time finding something that fits my needs.
I used one approach which goes in the same direction but i would rather say its a dynamic approach instead of generic. Its now working pretty well and we are able to generate all desired filters automatically by just giving the search entity. I also thought the criteria api is the way to go but after a while it just got too messy with all the side effects and i turned around creating the query string with parameters myself.
I created an entityscanner which takes all domain entities and generates filterdefinition objects for each desired filter. This scanner takes an entity and follows properties up to a certain level (to keep the amount of filters at bay). I cannot give you the code here since that belongs to a customer but the approach i can provide.
What i needed in the filterdefinition is this: entitytype, propertypath, propertytype, valuesexpression in case we render options (think masterdata), joins needed (to avoid joining several times the same tables), open/closed bracket. This is the definition of a filter.
Then you need a value object holding the current configuration of a user: Inputvalue, operator (>=), brackets, filter link (and/or) .
With this we can render a completly dynamic filter engine with some small limitations. I.e i did not implement parent searches of the same entity yet.
You might start simple an generate a sub query for each filter. Like: where id in (select ....) and/or id in (select ...) This works ok if the amount of entities is not too high but you will feel the performance penalty of several subqueries if the amount of rows in the domain entity table is high.
Then you dive in and find a way to separate the joins needed for a property path and in the querycreator you fiddle out the way of joining entities only again if neccessary.
As said. Start simple. Take first level properties of simple types like string and create your query engine. Enhance it by following specific entity joins and after you can go crazy and introduce expressions fetching options for a select rendering or use the conversion service for input parameters and so on.

Resources