JPA CRUD Operation in Spring boot

When we talk about Spring boot, Most important aspect of using it is the ease of doing database operation in it which is because of JPA used in spring boot.

In today’s article, we will talk about JPA CRUD Operation using JpaRepository.

#Objective

To Understand CRUD Operation and how to implement it in the Spring boot

Lets Start –

Here we will create one Application where we will have

  1. One Controller
  2. One Service class
  3. One repository class.

Now This application will do 4 simple operations i.e

Create /Read/Update/Delete User using Jpa.

Many of you wonder what is JPA- The Java Persistence API is a Java application programming interface specification that describes the management of relational data in applications using Java Platform, Standard Edition and Java Platform, Enterprise Edition. Wikipedia

Learn About : Top 5 Online Courses for Spring Boot Developers

Let’s Go

First, Let see the Structure of our Project

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>in.learnspringboot</groupId>
  <artifactId>JpaDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>JpaDemo</name>
  <description>Log4j2 Implementation</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <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>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <scope>runtime</scope>
    </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>
      </plugin>
    </plugins>
  </build>


</project>

we are creating one Entity Class of User – It will have have

-firstName
-lastName
-Address
-Id

User.java

package in.learnspringboot.model;

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

@Entity
public class User {
  
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  
  private String firstname;
  
  private String lastname;
  
  private String address;

  public Long getId() {
    return id;
  }

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

  public String getFirstname() {
    return firstname;
  }

  public void setFirstname(String firstname) {
    this.firstname = firstname;
  }

  public String getLastname() {
    return lastname;
  }

  public void setLastname(String lastname) {
    this.lastname = lastname;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  public User() {
    super();
  }

  @Override
  public String toString() {
    return "User [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", address=" + address + "]";
  }
  
  
  

  
  
}

Here we have defined

@Entity – this annotation is used to tell the hibernate that this class will be the schema of one of the tables in DB.




@Id – this donate the primary key of the class and @GeneratedValue – this is used to tell the hibernate how the id will be generated.

Others are @Column @Tables @NotNull etc

Now we will create one Controller which will have all the 4 Operation APIs Endpoints

package in.learnspringboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import in.learnspringboot.model.User;
import in.learnspringboot.service.UserService;

@RestController
public class UserRestController {

//	NOTE - The below Controller code is just to demostrate dont use the same in real project 
//	you need to handle exception and validation
  
  @Autowired
  UserService userService;
  
  @GetMapping("/user/{id}")
  public ResponseEntity<User> getUser(@PathVariable("id") Long id){
    
    return ResponseEntity.ok(userService.getOne(id));
  }
  
  
  @PostMapping("/user")
  public ResponseEntity<Void> createUser(@RequestBody @Validated User user){
    
    User user1 =userService.createUser(user);
    if(user1==null)
    {
      return ResponseEntity.badRequest().build();
    }
    
    return ResponseEntity.ok().build();
    
  }
  
  
  @PutMapping("/user")
  public ResponseEntity<User> updateUser(@RequestBody @Validated User user){
    User user1 =userService.createUser(user);
    if(user1==null)
    {
      return ResponseEntity.badRequest().build();
    }
    
    return ResponseEntity.ok().build();
    
  }
  
  @DeleteMapping("/user/{id}")
  public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id){
    
    userService.deleteUser(id);
    return ResponseEntity.ok().build();
  }

}

After this, we will see the Service Class

UserService.java

package in.learnspringboot.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import in.learnspringboot.model.User;
import in.learnspringboot.repository.UserRepository;

@Service
public class UserServiceImpl implements UserService{

  @Autowired
  UserRepository userRepository;
  
  @Override
  public List<User> getAll() {
    return userRepository.findAll();
  
  }

  @Override
  public User getOne(Long id) {
     Optional<User> users =userRepository.findById(id);
     if(users.isPresent())
       return users.get();
     return null;
  
  }

  @Override
  public User createUser(User user) {
    return userRepository.save(user);
  
  }

  @Override
  public boolean deleteUser(Long id) {
    userRepository.delete(userRepository.findById(id).get());
    return true;
  }

  @Override
  public User update(User user) {
    User user1 =userRepository.findById(user.getId()).get();
    if(user==null)
      return null;
    
    user1.setLastname(user.getLastname());
    
    return userRepository.save(user1);
    
    
  }

}

And the Most Important Class




UserRepository.java

package in.learnspringboot.repository;

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

import in.learnspringboot.model.User;

public interface UserRepository extends JpaRepository<User, Long>{
  
  

}

Point to remember

  • Here We have not created the Table, It will be created by Hibernate only
  • We are using Embedded Database for the Db Operations.

Now let’s Discuss the different method of JpaRepository.

findById() This method is a Query Method

save() – this method will be used to save the object into the table

Important

QueryMethod –

We can create the method which will autogenerate the query in the backend in JPA repository.

Let see the example

if I need to find the user using its First Name – I have 2 Options –

Using QueryMethod –

User findByFirstname(String fistName);

So Basically we can write any QueryMethod Like

findBy<classVaraibleName>();

Using Query

@Query("SELECT A FROM User A WHERE A.firstName = :firstName )
User findUsingFirstName(@Param("firstName) String firstName );

I hope you have got the use of JPA and how we can simply create the Application and CRUD Operation using it.




If You have any issue, Please leave us a comment, Happy to help

Thanks for reading

Noeik

You may also like...

5 Responses

  1. Anil says:

    What is @PatchMapping

    • programinjavaadmin says:

      @PatchMapping is used when we want to partially changed the data in API , Basically it is the alternate option of @RequestMapping (method= RequestMethod.PATCH)

  2. Neha says:

    How to do exception handling in rest API by @controlleradvice

  1. December 2, 2018

    […] Read More: JPA CRUD Operation in Spring boot […]

Leave a Reply

Your email address will not be published. Required fields are marked *