Spring Data JPA Distinct example

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.

Hibernate Tutorial with Spring Boot and MySql/Oracle.