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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Spring Data: Easy MongoDB Migration Using Mongock
  • Fast Data Access Part 2: From Manual Hacks to Modern Stacks
  • How Spring Boot Starters Integrate With Your Project

Trending

  • XMLSerializer - Removing Namespace & Schema Declarations xmlns:xsi xml:xsd
  • Designing Effective Meetings in Tech: From Time Wasters to Strategic Tools
  • Android Software Stack and Terminology (Tutorial 01)
  • Stop Leap-Second AI Drift in IoT Streams With PySpark
  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
7.3K 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
  • Fast Data Access Part 2: From Manual Hacks to Modern Stacks
  • How Spring Boot Starters Integrate With Your Project

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook