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

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

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

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Spring Data: Easy MongoDB Migration Using Mongock
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach

Trending

  • Infrastructure as Code (IaC) Beyond the Basics
  • Driving DevOps With Smart, Scalable Testing
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Advancing Robot Vision and Control
  1. DZone
  2. Data Engineering
  3. Data
  4. Introduction to Spring Boot and JDBCTemplate: Refactoring to SpringData JPA

Introduction to Spring Boot and JDBCTemplate: Refactoring to SpringData JPA

Introduction to Spring Boot and JDBCTemplate: Refactoring to SpringData JPA.

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
May. 07, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
6.9K Views

Join the DZone community and get the full member experience.

Join For Free

Refactoring is the process of modifying a software system without changing its desirable behavior. It was necessary to have an application integrated with the relational database using the Spring JDBC Template in the first parts. The Spring JDBC Template is a powerful tool that facilitates productivity. However, there is a way to simplify the code even further with Spring Data JPA. The purpose of this post is to refactor the project to use Spring Data JPA.

Spring Data JPA, part of the larger Spring Data family, makes it easy to implement JPA-based repositories easily. This module deals with enhanced support for JPA-based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.

A safe code refactoring requires the use of tests to ensure that the compartment is not changed. The use of tests, fortunately, is adopted as a minimum standard, including several methodologies such as TDD that preach the creation of tests at the beginning of the development process.

The first step in refactoring is the dependency upgrade to use Spring Data JPA.

XML
 




x


 
1
<dependency> 
2
    <groupId>org.springframework.boot</groupId> 
3
    <artifactId>spring-boot-starter-data-jpa</artifactId> 
4
</dependency> 



JPA is an annotation-driven framework, thus, it will put annotations in the Car entity.

Java
 




xxxxxxxxxx
1
31


 
1
@Entity 
2
public class Car { 
3

          
4
    @Id 
5
    @GeneratedValue(strategy= GenerationType.IDENTITY) 
6
    private Long id; 
7

          
8
    @Column 
9
    private String name; 
10

          
11
    @Column 
12
    private String city; 
13

          
14
    @Column 
15
    private String model; 
16

          
17
    @Column 
18
    private String color; 
19
  
20
} 



These annotations will reduce the boilerplate, and it will remove the RowMapper implementation. The next step is to delete the DAO class and use the repository interface instead. Spring Data repository abstraction aims to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. 

Java
 




xxxxxxxxxx
1


 
1
public interface CarRepository extends PagingAndSortingRepository<Car, Long> { 
2

          
3
}



We'll replace the DAO to use CarRepository instead in the service layer. Yeap, both DAO and Repository will decouple the service with the data abstraction. However, they are different. 

Java
 




xxxxxxxxxx
1
46


 
1
@Service 
2
public class CarService { 
3

          
4
    private final CarRepository repository; 
5
  
6
    private final CarMapper mapper; 
7

          
8

          
9
    @Autowired 
10
    public CarService(CarRepository repository, CarMapper mapper) { 
11
        this.repository = repository; 
12
        this.mapper = mapper; 
13
    } 
14

          
15
    public List<CarDTO> findAll(Pageable page) { 
16
        Stream<Car> stream = StreamSupport 
17
                .stream(repository.findAll(page) 
18
                        .spliterator(), false); 
19
        return stream.map(mapper::toDTO) 
20
                .collect(Collectors.toList()); 
21
    } 
22

          
23
    public Optional<CarDTO> findById(Long id) { 
24
        return repository.findById(id).map(mapper::toDTO); 
25
    } 
26

          
27
    public CarDTO insert(CarDTO dto) { 
28
        Car car = mapper.toEntity(dto); 
29
        return mapper.toDTO(repository.save(car)); 
30
    } 
31

          
32
    public CarDTO update(Long id, CarDTO dto) { 
33
        Car car = repository.findById(id) 
34
                .orElseThrow(() -> new EntityNotFoundException("Car does not find with the id " + id)); 
35
        car.update(mapper.toEntity(dto)); 
36
        repository.save(car); 
37
        return mapper.toDTO(car); 
38
    } 
39
  
40

          
41
    public void delete(Long id) { 
42
        repository.deleteById(id); 
43
    } 
44

          
45
} 



Spring Data dramatically simplifies the code, motivating the migration of this framework instead of Spring JDBC. In our simple example, with the migration, there was a reduction of three entire classes. This reduction of code tends to increase as the queries become more complex, for example, work with several join combinations. 


Spring Framework Spring Data Spring Boot Data (computing) Data access

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Spring Data: Easy MongoDB Migration Using Mongock
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach

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!