DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Testcontainers With Kotlin and Spring Data R2DBC

Trending

  • Implementing Explainable AI in CRM Using Stream Processing
  • Designing a Java Connector for Software Integrations
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • AI Agents: A New Era for Integration Professionals
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Use Spring Data JPA With Spring Boot 2

How to Use Spring Data JPA With Spring Boot 2

Get comfortable with the Spring Data family in this Spring Data JPA tutorial.

By 
Himanshu Kakar user avatar
Himanshu Kakar
·
Updated Mar. 04, 19 · Tutorial
Likes (20)
Comment
Save
Tweet
Share
65.2K Views

Join the DZone community and get the full member experience.

Join For Free

As 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 or SpringBootApplication 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);
}


JPA Repository Features

Query DSL

Advantages

  1. Utilize the work spent on creating your JPA entities.
  2. Less code less to maintain
  3. 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 of JpaRepository. 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....'Jpa Interface Query Dsl With Wrong Param Name.PNG

Query Methods

The query parser will match the following:

  1. 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
  2. queryBy..
  3. readBy..
  4. countBy..
  5. 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 the JapRepository method defined.

JPA Named Query

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:

  1. Optimistic locking: Achieved using the version parameter in the entity and annotated with @Version. If the version number doesn't match, throw theOptimisticLockingException.
  2. 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!

Spring Framework Spring Data Spring Boot Data (computing) Database

Opinions expressed by DZone contributors are their own.

Related

  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Testcontainers With Kotlin and Spring Data R2DBC

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!