Spring Data CrudRepository existsById()

In this tutorial, we will see about Spring Data CrudRepository existsById() Method using Spring Boot and Oracle.

Spring Data CrudRepository existsById()

CrudRepository interface extends Repository interface. In Spring Data JPA Repository is top-level interface in hierarchy. Here we are going to see existsById() method of CrudRepository. The existsById() method has been defined as below.

boolean existsById(ID id);

The CrudRepository existsById() method is used to check whether an entity exists in the database or not. It will return true if entity for given id exists in the database else false. Internally existsById() uses CrudRepository findById() method only.

Note – existsById(ID id)  returns boolean where as findById(ID id) returns Optional(Object). We can get object from Optional class using get() method(see more details here).

Spring Data CrudRepository existsById() Sample.

Let’s see in below code how we are going to use the CrudRepository existsById() method.

 

Let’s see an example of Spring Data JPA CrudRepository existsById() Method.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – springdataexistsById, ArtifactId – springdataexistsById and name – springdataexistsById) and click on finish. Keep packaging as the jar.

Modify pom.xml

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

Directory structure –

Spring Data CrudRepository save() Method

 

 

Student.java

StudentController.java

StudentRepository.java – interface

StudentService.java – interface

 

StudentServiceImpl.java

SpringMain.java

 

JpaConfig.java

application.properties

Let’s run the SpringMain class(run as java application).

Perform save operation first using below REST API.

Perform save operation first using below REST API.

http://localhost:9091/student/save

Request Data –

Response data –

 

 

Get operation.

API -http://localhost:9091/student/{id}

http://localhost:9091/student/1

Spring Data CrudRepository existsById()

Suppose you try to fetch Student entity on basis of id 2, you will get below response.

 

See brief about Spring Data JPA Repository hierarchy as below.

 

That’s all about Spring Data CrudRepository existsById().

You may like.

Other Spring Data JPA and Hibernate tutorials.

Spring Data JPA existsById() docs.

We have seen Spring Data CrudRepository existsById() method.ummu

Summary – Spring Data CrudRepository existsById() Method used to check whether an entity exists in the database or not. It will return true if entity for given id exists in the database else false.

Top