How to Use Spring Data JPA With Spring Boot 2
Get comfortable with the Spring Data family in this Spring Data JPA tutorial.
Join the DZone community and get the full member experience.
Join For FreeAs you may already be aware, Spring Data JPA is part of the larger Spring Data family. In this article, we are going to use Spring Data JPA along with Spring Boot to communicate with the MariaDB database.
Dependencies
With Spring Boot:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Configuration
The application.properties file presents in the src/main/resources to be configured as shown below:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://192.168.99.100:3306/test1
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
spring.jpa.show-sql=true
Scanning or Loading JPA Repositories
- If the repositories package is a sub-package of the Spring Boot main package, then
@SpringBootApplication
is enough, as it contains the@EnableAutoConfiguration
. - But if the repositories package is not a sub-package of the Spring main class package, in that case, we need to declare the repositories packages, as shown here:
@EnableJpaRepositories(basePackages = "com.springbootdev.examples.jpa.repositories")
This has to be provided in a configuration class orSpringBootApplication
class. - Similarly,
@EntityScan
can be used if the entity package is not a sub-package of the main Spring application package.
Create Repository
To create a repository, just extend the JapRepository
interface. It provides lot of methods by default.
Here is some helpful sample code for reference.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.mysql.demo.entity.User;
public interface UserJpaRepository extends JpaRepository<User, Integer>{
}
There is no implementation required for this interface. It can be directly injected and used in the service class. But if it doesn't provide the method, we can define in it and use it — no implementation required.
public interface UserJpaRepository extends JpaRepository<User, Integer>{
List<User> findByName(String name);
}
Query DSL
Advantages
- Utilize the work spent on creating your JPA entities.
- Less code less to maintain
- Check your queries on startup rather than on runtime. In the image below, we defined a method
findByNames
in an interface, which is an extension ofJpaRepository
. But our entity class has a parameter name. So when we try to run the application, we get the following error: 'No property name found....'
Query Methods
The query parser will match the following:
- findBy.. : returns a listfindBy..Is, findBy..Equals, findBy..Not, findBy..Like, findBy..NotLike, findBy..StartingWith, findBy..EndingWith, findBy..ContainingFor number data types: findBy..LessThan, findBy..LessThanEquals, findBy..GreaterThan, findBy..GreaterThanEqualDate comparison: findBy..Before, findBy..After, findBy..BetweenFor boolean comparison: findBy..True, findBy..FalseNull checks: findBy..IsNull, findBy..IsNotNullFor collection comparison, In, notIn: findBy..In(Collection str), findBy..NotIn(Collection str)Ignore case: findBy..IgnoreCase, findBy..StartingWithIgnoreCaseOrder : findBy..OrderByCountryAsc, findBy..OrderByCountryDescTo limit the results:findFirstBy.., findTop5By.., findDistinct..By..s
- queryBy..
- readBy..
- countBy..
- getBy..
This criterion uses the JPA entity attributes names. And, this includes multiple criteria combined with 'And' and 'Or'Eg:findByStateAndCount(String sate, String countrys).
Query Annotation
Sometimes, the query dsl method names become too long. Or sometimes, we want to the use the existing JPQL. In those scenarios, we can use the query annotation.
@Query("select u from User u where u.age > :age1 and u.age < :age2")
List<User> queryByAgeRange(@Param("age1") int age1, @Param("age2") int age2);
Named Query
Named query is defined in the Entity class with the @NamedQuery
annotation.
For example: @NamedQuery(name="Model.namedFindAllModelsByType", query="select m from Model m where m.modelType.name= :name")
To use the named query in the JpaRepository
interface, we need to do the following:
- One way is to define your
JpaRepository
interface method with the name of the named query. - Another way is to use the
@Query
annotation over theJapRepository
method defined.
Native Queries
To mark a query as native, in the query annotation, use the native param = true.
Named Native Queries
This works similarly as the named query.
Pagination
Sometimes, for a large set of data, we might want to fetch the data in chunks. Then, we can go to pagination. Pagination is provided by the PagingAndSortingRepository
interface and the findAll(Pageable pag)
method.
public Page<User> getAllUsers(int page, int size) {
return userRepo.findAll(PageRequest.of(page, size));
}
Sorting
PagingAndSortingRepository
--> findAll(Sort sort)
public List<User> getAllUsersSorted(String paramname) {
return userRepo.findAll(Sort.by(Sort.Direction.ASC,paramname));
}
Auditing
To enable JPA auditing, use @EnableJpaAuditing
in the configuration class.
Here are the annotations used:
-
@CreatedBy
-
@CreatedDate
-
@LastModifiedBy
-
@LastModifiedDate
Locking
There are two types of locking strategies:
- Optimistic locking: Achieved using the version parameter in the entity and annotated with
@Version
. If the version number doesn't match, throw theOptimisticLockingException
. - Pessimistic locking: Long term locks the data for the transaction duration, preventing others from accessing the data until the transaction commits.
The locking strategy is stated over the repository method using the @Lock
annotation.
@Lock(LockModeType.PESSIMISTIC_WRITE)
List<User> findByAgeOrName(int age, String name);
Connection Pool
Spring Boot 2 provides by default Hikari Connection pool. In comparison to other connection pool providers its very lightweight and has better performance.
Hikari Pool in comparison to other data sources provides lot of configurations. Its configurations starts with spring.datasource.hikari.. One of the must have configurations is provided below.
maxLifetime :
This property controls the maximum lifetime of a connection in the pool. An in-use connection will never be retired, only when it is closed will it then be removed. On a connection-by-connection basis, minor negative attenuation is applied to avoid mass-extinction in the pool. We strongly recommend setting this value, and it should be several seconds shorter than any database or infrastructure imposed connection time limit. A value of 0 indicates no maximum lifetime (infinite lifetime), subject of course to the idleTimeout
setting. Default: 1800000 (30 minutes)
Details of all the configurations https://github.com/brettwooldridge/HikariCP#configuration-knobs-baby
That's all for now. Let us know what you thought of this Spring Data JPA tutorial in the comments below. Happy coding!
Opinions expressed by DZone contributors are their own.
Comments