Spring Data JPA Not Null

In this post, we will see how to write a custom Spring Data JPA Not Null method in the repository interface.

Note – IsNotNull & NotNull both will work same. Also, Check the Spring Data JPA IsNull repository method.

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;
	
}

Let’s see how to write a custom Spring Data Jpa Not Null method for different use cases.

Example 1 – Suppose we want only to return those records where the name is not null.

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {

    List<Student> findByNameNotNull();
}

The query generated for the above example.

Hibernate: 
    select
        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 is not null

Example 2 – Suppose we want only to return those records where the name is not null and the university also not null.

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {

    List<Student> findByNameNotNullAndUniversityNotNull();
}

The query generated for the above example.

Hibernate: 
    select
        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 is not null
        ) 
        and (
            student0_.university is not null
        )

Spring Data JPA Not Null example using Spring Boot and MySql

Project structure

Spring Data JPA Not Null example

Add maven dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>springdatajpa</groupId>
    <artifactId>springdatajpa</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

</project>

Define entity Student.java

package com.javatute.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

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

    @Column(name = "roll_number")
    private String rollNumber;

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

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getRollNumber() {
        return rollNumber;
    }

    public void setRollNumber(String rollNumber) {
        this.rollNumber = rollNumber;
    }

    public String getUniversity() {
        return university;
    }

    public void setUniversity(String university) {
        this.university = university;
    }
}

StudentService.java

package com.javatute.service;

import com.javatute.entity.Student;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public interface StudentService {

    public Student save(Student student);

    public Student update(Student student);

    public Student get(Long id);

    /*public List<Student> getStudents(String name);*/

    public List<Student> getStudents();

    public void delete(Student student);
}

StudentRepository.java

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> findByNameNotNull();
    List<Student> findByNameNotNullAndUniversityNotNull();
}

StudentServiceImpl.java

package com.javatute.serviceimpl;

import com.javatute.entity.Student;
import com.javatute.repository.StudentRepository;
import com.javatute.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;


    @Transactional
    public Student save(Student student) {
        Student createResponse = null;
        createResponse = studentRepository.save(student);
        //createResponse = studentRepository.save(student);
        return createResponse;
    }

    @Transactional
    public Student update(Student student) {
        Student updateResponse = studentRepository.save(student);
        return updateResponse;
    }

    @Transactional
    public Student get(Long id) {
        Optional<Student> response = studentRepository.findById(id);
        Student getResponse = response.get();
        //String sql = "select name from student";
        //List<String> names =  jdbcTemplate.queryForList(sql,  String.class);
        //return names;
        return getResponse;
    }

    @Transactional
    public List<Student> getStudents() {
        List<Student> response = new ArrayList<>();
       response = studentRepository.findByNameNotNullAndUniversityNotNull();
        //Student getResponse = response.get();
        //String sql = "select name from student";
        //List<String> names =  jdbcTemplate.queryForList(sql,  String.class);
        //return names;
        return response;
    }

    @Transactional
    public void delete(Student student) {
        studentRepository.delete(student);
    }
}

StudentServiceImpl.java

package com.javatute.controller;

import com.javatute.entity.Student;
import com.javatute.repository.StudentRepository;
import com.javatute.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentRepository studentRepository;

    @PostMapping("/create")
    public Student createStudent1(@RequestBody Student student) {
        Student createResponse = studentService.save(student);
        return createResponse;
    }

	@PutMapping("/update")
	public Student updateStudent(@RequestBody Student student) {
		Student updateResponse = studentService.update(student);
		return updateResponse;
	}

/*	@GetMapping("/{id}")
	public Student getStudent(@PathVariable Long id) {
		Student getReponse = studentService.get(id);
		return getReponse;
	}*/

/*	@GetMapping("/{name}")
	public List<Student> getStudent(@PathVariable String name) {
		List<Student> getReponse = studentService.getStudents(name);
		return getReponse;
	}*/

	@GetMapping("/{students}")
	public List<Student> getStudent() {
		List<Student> getReponse = studentService.getStudents();
		return getReponse;
	}
	@DeleteMapping("/delete")
	public String deleteStudent(@RequestBody Student student) {
		studentService.delete(student);
		return "Record deleted succesfully";
	}

	@GetMapping("/getcustomfieldsbasisofuserinput")
	public String deleteStudent(@RequestParam String fields) {
		System.out.println(fields);
		//studentService.delete(student);
		return "Record deleted succesfully";
	}

}

JpaConfig.java

package com.javatute.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "com.javatute.repository")
public class JpaConfig {

}

SpringMain.java

package com.javatute.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@ComponentScan(basePackages = "com.javatute.*")
@EntityScan("com.javatute.*")
public class SpringMain {
    public static void main(String[] args) {
        SpringApplication.run(SpringMain.class, args);
    }
}

That’s all about Spring Data JPA Not Null example using spring boot and MySQL.

Download the example from GitHub.

Spring Data JPA Docs.

You may like