Social Media

Spring Data JPA

The DAO pattern is one of the most common patterns I see in JPA. It’s a good pattern, and is generally implemented in the form set out in this article dzone. It’s a good pattern, but the issue I have in development is that I end up writing boilerplate code to provide the same features.

This is where Spring Data JPA steps in and frees you up from writing DAO implementations.


Consider the following JPA entity –

[sourcecode lang=”java”] package com.glenware.entity;

@Table(name = "PARKRUN_COURSE")
public class ParkrunCourse implements Serializable {
private static final long serialVersionUID = 1L;

@Column(name = "PARKRUN_COURSE_ID")
private Long parkrunCourseId;

@Size(max = 200)
@Column(name = "NAME")
private String name;

@Size(max = 200)
@Column(name = "DESCRIPTION")
private String description;

// Getters And Setters Not shown


Steps –

1. Model pom.xml –

[sourcecode lang=”xml”] <dependency>

2. Create a implementation of the repository interface for –

[sourcecode lang=”java”] package com.glenware.repository;


public interface ParkrunCourseRepository extends CrudRepository<ParkrunCourse, Long> {

Amend your Spring file –

[sourcecode lang=”xml”] <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns=""

<jpa:repositories base-package=" com.glenware.repository" />


3. Service – Create method and implementation to access this repository from the Service layer

[sourcecode lang=”java”] package com.glenware.service;

public interface ParkrunCourseService {
long getTotalParkrunCourses();

Create Implementation –

[sourcecode lang=”java”] package com.glenware.service;

public class ParkrunCourseServiceImpl implements ParkrunCourseService {

private ParkrunCourseRepository parkrunCourseRepository;

public long getTotalParkrunCourses () {
return parkrunCourseRepository.count();


CrudRepository defines methods for delete, find, and saving JPA objects. There is also a specialist interface for PagingAndSortingRepository

And its even easier to implement using Spring Boot!

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About or on my consultancy website Glendevon Software

follow me on:

Leave a Comment: