I want to implement a search function with five optional variables and in every combination, so a switch/case is not a possible way. So i can't use the build in spring boot functions, because they are not dynamic (correct me if i'm wrong). I know there is the @query annotation in the crudrepository, but there is no way to write a query with optional parameters? I tried to write my own database access with jpa, without the help of spring boot CrudRepository. I read in the manual this should work:
@Autowired
@PersistenceContext
private EntityManager em;
@Transactional
public List<Persons>searchPersons(params...){}
But here is the problem, my EntityManager is always null and i have no idea why. I searched some hours and found nothing.
Maybe you guys know a way to write a dynamic SQL query in Spring Boot. Is there a way in the CrudRepository to define optional parameters for the query? Btw i use a postgreSQL database.
Many thanks for your help.
You might want to have a look at Specifications.
For that to work, your repository interface needs to implement JpaSpecificationExecutor
.
You can use a custom repository (create your own interface, write one Impl class for it and extend your repository by that interface.
You should then have:
PersonRepositoryCustom
PersonRepositoryCustomImpl
Next, you implement a query, using the EntityManager autowired into your repository. You can do this by using JPQL or the JPA 2.1 Criteria API.
For each parameter, have a condition to add it to the query itself, as well as the prepared statement parameters. That way, you can build a dynamic query.
The following thread is related: Best way to create JPA query that might contain a parameter or might not
I know this question is old but to anyone coming here interested in implementing dynamic SQL queries , check out these two blog posts, they are great.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.