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
  • Intro to Spring Data MongoDB Reactive and How to Move It to the Cloud
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA

Trending

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  • Designing a Java Connector for Software Integrations
  1. DZone
  2. Data Engineering
  3. Databases
  4. Add Custom Functionality to a Spring Data Repository

Add Custom Functionality to a Spring Data Repository

This how-to article explains how to get some extra mileage and flexibility out of Spring Data repositories.

By 
Emmanouil Gkatziouras user avatar
Emmanouil Gkatziouras
DZone Core CORE ·
Jun. 06, 16 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
6.0K Views

Join the DZone community and get the full member experience.

Join For Free

Spring data is pretty convenient and speeds up development, avoiding boilerplate code.

However, there are cases where annotation queries are not enough for the custom functionality you might want to achieve.

Therefore, Spring Data allows us to add custom methods to a Spring Data Repository.

I will use the same project structure from a previous blog post.

Here, we have an entity called Employee:

package com.gkatzioura.springdata.jpa.persistence.entity;

import javax.persistence.*;

/**
 * Created by gkatzioura on 6/2/16.
 */
@Entity
@Table(name = "employee", schema="spring_data_jpa_example")
public class Employee {

 @Id
 @Column(name = "id")
 @GeneratedValue(strategy = GenerationType.SEQUENCE)
 private Long id;

 @Column(name = "firstname")
 private String firstName;

 @Column(name = "lastname")
 private String lastname;

 @Column(name = "email")
 private String email;

 @Column(name = "age")
 private Integer age;

 @Column(name = "salary")
 private Integer salary;

 public Long getId() {
 return id;
 }

 public void setId(Long id) {
 this.id = id;
 }

 public String getFirstName() {
 return firstName;
 }

 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

 public String getLastname() {
 return lastname;
 }

 public void setLastname(String lastname) {
 this.lastname = lastname;
 }

 public String getEmail() {
 return email;
 }

 public void setEmail(String email) {
 this.email = email;
 }

 public Integer getAge() {
 return age;
 }

 public void setAge(Integer age) {
 this.age = age;
 }

 public Integer getSalary() {
 return salary;
 }

 public void setSalary(Integer salary) {
 this.salary = salary;
 }
}

And the Spring Data repository:

package com.gkatzioura.springdata.jpa.persistence.repository;

import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by gkatzioura on 6/2/16.
 */
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long>{

}

Suppose that we want to add some custom sql functionality for example querying with a LIKE statement and joining with a table that is not mapped as an entity.

This is for demonstration purposes only. For your project you might have a better schema. Plus spring data comes with out of the box functionality for like statements, look at EndingWith, Containing, StartingWith.

We shall create the table bonus and add a reference to the employee table.

set schema 'spring_data_jpa_example';
 
create table bonus(
    id serial primary key,
    employee_id integer,
    amount real,
    foreign key (employee_id) references employee (id),
    unique (employee_id)
    );
 
insert into bonus
( employee_id, amount)
VALUES(1, 100); 

The sql query that we want to implement will query for employees whose name starts with a specified text and a bonus bigger than a certain amount.
In jdbc we have to pass our variable concatenated with the character ‘%’.

So what we need is a native jpa query like this one

Query query = entityManager.createNativeQuery("select e.* from spring_data_jpa_example.bonus b, spring_data_jpa_example.employee e\n" +
        "where e.id = b.employee_id " +
        "and e.firstname LIKE ? " +
        "and b.amount> ? ", Employee.class);
query.setParameter(1, firstName + "%");
query.setParameter(2, bonusAmount);

In order to add this functionality to our Spring Data repository, we have to add an interface.

It is mandatory for our interface to follow the naming convention of ${Original Repository name}Custom.

Therefore, the interface describing our custom functionality should be:

package com.gkatzioura.springdata.jpa.persistence.repository;
 
import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
 
import java.util.List;
 
/**
 * Created by gkatzioura on 6/3/16.
 */
public interface EmployeeRepositoryCustom {
 
    List<Employee> getFirstNamesLikeAndBonusBigger(String firstName, Double bonusAmount);
 
}

And the implementation should be:

package com.gkatzioura.springdata.jpa.persistence.repository;
 
import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
 
/**
 * Created by gkatzioura on 6/3/16.
 */
@Repository
@Transactional(readOnly = true)
public class EmployeeRepositoryImpl implements EmployeeRepositoryCustom {
 
    @PersistenceContext
    EntityManager entityManager;
 
    @Override
    public List<Employee> getFirstNamesLikeAndBonusBigger(String firstName, Double bonusAmount) {
        Query query = entityManager.createNativeQuery("select e.* from spring_data_jpa_example.bonus b, spring_data_jpa_example.employee e\n" +
                "where e.id = b.employee_id " +
                "and e.firstname LIKE ? " +
                "and b.amount> ? ", Employee.class);
        query.setParameter(1, firstName + "%");
        query.setParameter(2, bonusAmount);
 
        return query.getResultList();
    }
}

And we should change our original Spring Data repository in order to inherit the custom functionality.

package com.gkatzioura.springdata.jpa.persistence.repository;

import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by gkatzioura on 6/2/16.
 */
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long>, EmployeeRepositoryCustom {
}

Seems like a nice way of composing it.

Now let’s add a method to a controller that will call this custom method:

	
package com.gkatzioura.springdata.jpa.controller;
 
        import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
        import com.gkatzioura.springdata.jpa.persistence.repository.EmployeeRepository;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RequestParam;
        import org.springframework.web.bind.annotation.RestController;
 
        import java.util.List;
 
/**
 * Created by gkatzioura on 6/2/16.
 */
@RestController
public class TestController {
 
    @Autowired
    private EmployeeRepository employeeRepository;
 
    @RequestMapping("/employee")
    public List<Employee> getTest() {
 
        return employeeRepository.findAll();
    }
 
    @RequestMapping("/employee/filter")
    public List<Employee> getFiltered(String firstName,@RequestParam(defaultValue = "0") Double bonusAmount) {
 
        return employeeRepository.getFirstNamesLikeAndBonusBigger(firstName,bonusAmount);
    }
 
}

The source code can be found on GitHub.

Related Refcard:

Core Spring Data

Spring Framework Spring Data

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Intro to Spring Data MongoDB Reactive and How to Move It to the Cloud
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA

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!