I have an application that uses Spring Boot Data jpa . So far i am using a repository like this
public interface StudentRepository extends CrudRepository<StudentEntity, Integer>{
@Query(value = ""
+ "SELECT s.studentname "
+ "FROM studententity s, "
+ " courseentity c "
+ "WHERE s.courseid = c.courseid "
+ " AND s.courseid IN (SELECT c.courseid "
+ " FROM courseentity c "
+ " WHERE c.coursename = ?1)")
List<String> nameByCourse(String coursename);
}
How can i make use of Criteria Query that Hibernate provides for such cases in a Spring Boot Application
From the
docs
Define an interface like so
Then define a custom implementation of this interface like so
Now you can extend this custom repository implementaion in your JPA repository like so.
Learn more about criteria query and criteria builder
here
JPA 2 introduces a criteria API that can be used to build queries programmatically.
You can extend a new interface from
JpaSpecificationExecutor
Then create a customer specs
For more details, refer this spring doc here
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications
you can refer to Query creation into spring data JPA documentation and take a look at the table, JPA give multiple Query creation from method names where you can avoid using a String query
It's very complicated to create specifications using JPA Criteria because the API is very verbose and instrusive.
With the Lambda JDK 8, you can create high very typed-queries using simples predicates.
You can isolate the conditions and to reuse in others queries, ie, specifications.
https://github.com/naskarlab/fluent-query
https://github.com/naskarlab/fluent-query-eclipselink
With
Spring-boot-jpa
you are able to useentityManager
nearly everywhere. The most commom way is to create an owninterface
for custom methods.Then implement this interface to a service class where you are able to autowire and use the
entityManager
:You can also decide to implement your
StudentRepository
to your newStudentCustomRepositoryServiceImpl
class.According to Spring doc HibernateTemplate:
While according to Hibernate doc:
So its better to use JPQL Criteria:JPA Criteria API Queries
Example:
where entityManager should be @Autowired. For detail info, see above link