In this post, we are going to see Spring Data JPA Distinct example using MySql. We are going to write a custom repository method
using Spring Data JPA distinct.
Consider we have an entity called Student.java
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "name")
private String name;
@Column(name = "roll_number")
private String rollNumber;
@Column(name = "university")
String university;
}
Spring Data JPA Distinct repository method example
List<Student> findDistinctByName(String name);
The query was generated for the above repository method.
select
distinct student0_.id as id1_0_,
student0_.name as name2_0_,
student0_.roll_number as roll_num3_0_,
student0_.university as universi4_0_
from
student student0_
where
student0_.name=?
Some more use cases – Let’s see how to write a custom repository method for Spring Data JPA distinct rows with field in list
List<Student> findDistinctByNameNotIn(List<String> names);
Query generated
select
distinct student0_.id as id1_0_,
student0_.name as name2_0_,
student0_.roll_number as roll_num3_0_,
student0_.university as universi4_0_
from
student student0_
where
student0_.name not in (
?
)
Repository interface
package com.javatute.repository;
import com.javatute.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
import java.util.List;
@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {
List<Student> findDistinctByNameNotIn(List<String> names);
List<Student> findDistinctByName(String name);
}
Spring Data JPA tutorials.
- CrudRepository Methods Example.
- Difference between CrudRepository and JpaRepository in Spring Data JPA.
- Difference between Repository and CrudRepository
- Spring Data JPA Query Methods/Repository Methods.
- How to write custom method in the repository in Spring Data JPA
- How to create a custom repository in Spring Data JPA
Hibernate Tutorial with Spring Boot and MySql/Oracle.
- Inheritance Mapping in Hibernate with Spring Boot.
- Association Mapping in Hibernate with Spring Boot.
- Hibernate First Level Cache example with Spring Boot.
- Hibernate/JPA EhCache Configuration Example with Spring Boot.
- Hibernate Lazy vs Eager loading Example with Spring Boot.
- JPA and Hibernate Cascade Types example with Spring Boot