Spring Data JPA exists by field with Example





In this article, you will learn about Data JPA exists projection in repository query derivation with full coding example.

Read More:

Assume that we have a scenario where we need to check whether the given email address is exists in the database before saving to the database.

We can easily achieve this by writing Data JPA query method using existsBy. To create query method in JPA, we need to create a method like this –

Boolean existsByEmail(String email);

To check the existence of an item we use the keyword exitsBy followed by the field name in which we want to check the existence. For ex: existsByName(), findByEmail() etc.,

Complete example


Let’s create a step-by-step spring boot project and create query method for checking the existence of an item.

Create database and insert sample data


Open MySQL workbench and execute the following commands

CREATE DATABASE demodb;

USE demodb;

CREATE TABLE tbl_users
(
	id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL
);

INSERT INTO tbl_users(email, password) VALUES ("[email protected]", "12345");
INSERT INTO tbl_users(email, password) VALUES ("[email protected]", "12345");

We have created the table tbl_users which contains 3 fields. We have inserted the sample data as well.

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>findbyfieldname</artifactId>
	<version>v1</version>
	<name>findbyfieldname</name>
	<description>Spring boot data jpa find by field name</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container.




spring-boot-devtools dependency for automatic reloads or live reload of applications. spring-boot-starter-data-jpa dependency is a starter for using Spring Data JPA with Hibernate. lombok dependency is a java library that will reduce the boilerplate code that we usually write inside every entity class like setters, getters, and toString()

Create an entity class


Create User.java inside the in.bushansirgur.springboot.entity package and add the following content

package in.bushansirgur.springdatajpa.entity;

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

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Table(name = "tbl_users")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;
	
	private String email;
	
	private String password; 
}
  • @Data annotation which is a Lombok annotation, that will automatically create setters, getters, toString(), and equals() for us.
  • @Entity is a mandatory annotation that indicates that this class is a JPA entity and is mapped with a database table.
  • @Table annotation is an optional annotation that contains the table info like table name.



  • @Id annotation is a mandatory annotation that marks a field as the primary key

Create a Repository


Create an interface UserRepository.java inside the in.bushansirgur.springboot.repos package and add the following content

package in.bushansirgur.springdatajpa.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import in.bushansirgur.springdatajpa.entity.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long>{
	
	Boolean existsByEmail(String email);
}

@Repository annotates classes at the persistence layer, which will act as a database repository. We have extended this interface with JPARepository interface which will provide built-in methods to interact with the database also we can define query methods. We have defined a query method to check the existence of an email existsByEmail().

Create a Rest controller


Create UserController.java inside the in.bushansirgur.springboot.controller package and add the following content

package in.bushansirgur.springdatajpa.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import in.bushansirgur.springdatajpa.entity.User;
import in.bushansirgur.springdatajpa.repository.UserRepository;

@RestController
public class UserController {
	
	@Autowired
	private UserRepository userRepository;
	
	@PostMapping("/save")
	public ResponseEntity<User> saveUser(@RequestBody User user) {
		
		if (userRepository.existsByEmail(user.getEmail())) {
			throw new RuntimeException("Email is already exists");
		}
		
		return new ResponseEntity<User>(userRepository.save(user), HttpStatus.CREATED);
	}
}

We have autowired the UserRepository using @Autowired annotation. We have created a handler method, saveUser() which will call the repository methods save().

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the postman and enter the following URL –
Screenshot-2022-01-17-at-12-33-32-AM

References


That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.




Partners: kuinka siirtää rahaa paypal tilille mga valitus nettler aktia tunnistautuminen ei toimi online casinoer med dansk licens astropay kazino stranice online casino rofus sweet bonanza spiele pragmatic play big bass bonanza casinos en línea con astropay

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

This Post Has 2 Comments

Leave a Reply