Automate Document Signing using the DocuSign API
Dec. 14, 2022/
Java Persistence Query Language (JPQL) is a widely adopted API to access the database in Spring projects.
However, JPA provides another method called Criteria API. The Criteria API is an Object-Oriented query which means it provides type safe way to build database queries. Developers can check the correctness of the query at compilation time. In this blog I provide a common use case and demonstrate in Kotlin how developers can take advantage of the Criteria API.
Before I dive into it, let’s take a look at some important interfaces:
1.1 To keep things simple, let’s start with an Entity called Manager and the corresponding Spring repository: The Manager has only one field “title” and a primary key. Let’s also create a simple Specification to find Mangers with a given title:
1.2 Finally, in the Manager Service, we can create the function findManagersByTitle, which accepts a string parameter as an argument. It creates a specification entity of above ManagerFindByTitleQuery and passes it to the repository to get all managers with the given title:
2.1 JPA criteria can also handle relationships. Now we enhance the Manager entity with a OneToMany relationship to another Entity called Staff, which has only one field “department”:
2.2 To define a query to find managers who have staff in a specific department, the criteria can be updated with the join method:
2.3 Then we execute same call in the manager service:
3.1 JPA Criteria is a highly flexible and reusable query API. For example, to build this query: “find managers with a specific name and they must have staff in a specific department”, this is a combination of the first two examples, we create a new specification by using the Criteria builder and() API:
3.2 An advantage Of JPA Criteria is the Specification interface that can wrap predicates elegantly. Besides creating or updating existing queries, we can simply combine them via a Specification:
Conclusion In this blog, I demonstrated some basic use cases to access the database via JPA Criteria API. Though it looks like I am writing more code compare to using JPQL, as the query logic becomes more complex, the JPA Criteria API is more flexible and scales better to re-use complex queries.
11-17 York Street
Sydney NSW 2000
+61 2 82 94 80 67
© 2017-2023 Darumatic Pty Ltd. All Rights Reserved.