Spring Data optional parameter in query method
Too late to answer. Not sure about relationship between Bar and Goo. Check if Example can helps you.
It worked for me. I have a similar situation, entity User have set of attributes and there is findAll method which search user based on attributes(which are optional).
Example,
Class User{
String firstName;
String lastName;
String id;
}
Class UserService{
// All are optional
List<User> findBy(String firstName, String lastName, String id){
User u = new User();
u.setFirstName(firstName);
u.setLastName(lastName);
u.setId(id);
userRepository.findAll(Example.of(user));
// userRepository is a JpaRepository class
}
}
Spring Data JPA : Efficient Way to Invoke Repository Methods with Optional Parameters
You could use Specifications for that:
private Specification<YourEntity> toSpecification(UUID id, Status status, Long version) {
return (root, query, builder) -> {
Set<Predicate> predicates = new HashSet<>();
predicates.add(builder.equal(root.get("id"), id));
if (status != null) predicates.add(builder.equal(root.get("status"), status));
if (version != null) predicates.add(builder.equal(root.get("version"), version));
return builder.and(predicates.toArray(Predicate[]::new));
};
}
If you let your repository extend JpaSpecificationExecutor
you can use the build specification object like so:
Specification<YourEntity> specification = toSpecification(id, status, version);
Optional<YourEntity> result = repository.findOne(specification);
When using Hibernate Metamodel Generator you can also write builder.equal(YourEntity_.id, id)
instead of builder.equal(root.get("id"), id)
.
Related Topics
How to Group and Choose Lowest Value in SQL
Get Size of Large Object in Postgresql Query
Sql: Many-To-Many Table and Query
SQL - Find Missing Int Values in Mostly Ordered Sequential Series
SQL Server 2008 Cross Tab Query
Does Inner Join Performance Depends on Order of Tables
Can You Use a Column for the Timezone Parameter of at Time Zone in Presto/Athena
List All Tables in Postgresql Information_Schema
Create a One to Many Relationship Using SQL Server
How to Sort Values in Columns and Update Table
Remove Reverse Duplicates from an SQL Query
Sql: Group by on Consecutive Records
This Select Query Takes 180 Seconds to Finish
SQL Duplicate Column Name Error
How to Generate All Possible Data Combinations in SQL
How to Generate a Hierarchy Path in SQL That Leads to a Given Node