Spring Boot JPA Custom Query method

The CrudRepository interface provides the CRUD functionality in Spring JPA. It comes with default definitions of methods to execute common operations like find, save and delete records.

To work with a domain class, we need to inherit the CrudRepository to create a new interface corresponding to the domain class.

Here we will see how to write custom query method with parameter and sorting by the example of Student domain class with it’s StudentRepository.

1. Student.java
package com.firstfewlines.domain;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

@Entity
@Table(name="student_mst", schema = "public")
public class Student {

    int rollNo;
    String name;
    String stream;
    Date dateOfBirth;
    int totalMarks;

    @Id
    public int getRollNo() {
        return rollNo;
    }

    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStream() {
        return stream;
    }

    public void setStream(String stream) {
        this.stream = stream;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public int getTotalMarks() {
        return totalMarks;
    }

    public void setTotalMarks(int totalMarks) {
        this.totalMarks = totalMarks;
    }
}


2. StudentRepository.java

StudentRepository is the CRUD repository of Student. Here’s how we can write a custom method: findPassedForStream(…)

When the method is called, it executes the custom query defined with @Quary annotation by applying the parameter: stream

For the method: findByName(…), Spring JPA automatically creates appropriate implementation from the name of it.

package com.firstfewlines.repository;

import com.firstfewlines.domain.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends CrudRepository<Student, Integer> {
    
    @Query(value = "FROM Student WHERE stream = :stream AND totalMarks > 300 ORDER by totalMarks")
    List<Student> findPassedForStream(@Param('stream') String stream);
    
    List<Student> findByName(String name);
}



References:


Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus