{{announcement.body}}
{{announcement.title}}

Spring Data JPA Introduction - Part 2

DZone 's Guide to

Spring Data JPA Introduction - Part 2

The second part of this series on Spring Data JPA goes through the CRUD operations with a user profile.

· Java Zone ·
Free Resource

CRUD Operations

We will discuss about the following with a small implementation for creating a new user.

An introduction to CREATE Operation.

  • REST Controller (@RestController)
  • @PostMapping
  • @RequestBody
  • Service class (@Service)
  • Use Model classes.  
  • ResponseEntity to return status code, headers and body.
  • Unique Constraints.
  • Finder Methods.
  • Optional Class.

I use the following:

  • JDK 1.8
  • PostgreSQL
  • pgAdmin
  • Postman as my REST Client

Our Entity Model

User

User

The User Class

Java
 




xxxxxxxxxx
1
59


1
package com.notyfyd.entity;
2
 
          
3
import javax.persistence.*;
4
 
          
5
@Entity
6
@Table(name = "t_user")
7
public class User {
8
    @Id
9
    @GeneratedValue(strategy = GenerationType.IDENTITY)
10
    private Long id;
11
//    @Column(name = "firstName")
12
//    @Column(name="name")
13
    private String firstName;
14
    private String lastName;
15
    private String mobile;
16
    @Column(unique = true)
17
    private String email;
18
 
          
19
    public Long getId() {
20
        return id;
21
    }
22
 
          
23
    public void setId(Long id) {
24
        this.id = id;
25
    }
26
 
          
27
    public String getFirstName() {
28
        return firstName;
29
    }
30
 
          
31
    public void setFirstName(String firstName) {
32
        this.firstName = firstName;
33
    }
34
 
          
35
    public String getLastName() {
36
        return lastName;
37
    }
38
 
          
39
    public void setLastName(String lastName) {
40
        this.lastName = lastName;
41
    }
42
 
          
43
    public String getMobile() {
44
        return mobile;
45
    }
46
 
          
47
    public void setMobile(String mobile) {
48
        this.mobile = mobile;
49
    }
50
 
          
51
    public String getEmail() {
52
        return email;
53
    }
54
 
          
55
    public void setEmail(String email) {
56
        this.email = email;
57
    }
58
}
59
 
          


All we have to do here is to define the fields and write the getter and setter methods. Here, I have used the  @Column(unique=true). It sets an unique constraint on email, which is to say, duplicate entries of email will not be allowed.

User Repository Interface

Java
 




xxxxxxxxxx
1
12


 
1
package com.notyfyd.repository;
2
 
          
3
import com.notyfyd.entity.User;
4
import org.springframework.data.jpa.repository.JpaRepository;
5
import org.springframework.stereotype.Repository;
6
 
          
7
import java.util.Optional;
8
 
          
9
@Repository
10
public interface UserRepository extends JpaRepository<User, Long> {
11
    Optional<User> findByEmail(String email);
12
}



Here we are using a finder method which takes in an email and returns an Optional<User>. This can be used in conjunction with the isPresent() method to check whether it has returned an user. We don't have to check for null.

User Service Class

Java
 




xxxxxxxxxx
1
33


1
package com.notyfyd.service;
2
 
          
3
import com.notyfyd.entity.User;
4
import com.notyfyd.model.UserModel;
5
import com.notyfyd.repository.UserRepository;
6
import org.springframework.beans.factory.annotation.Autowired;
7
import org.springframework.http.ResponseEntity;
8
import org.springframework.stereotype.Service;
9
 
          
10
@Service
11
public class UserService {
12
    @Autowired
13
    private UserRepository userRepository;
14
 
          
15
    public ResponseEntity<Object> createUser(UserModel model) {
16
        User user = new User();
17
        if(userRepository.findByEmail(model.getEmail()).isPresent()){
18
            System.out.println("The email is already present");
19
            return ResponseEntity.badRequest().body("The Email is already Present, Failed to Create new User");
20
        } else {
21
            user.setFirstName(model.getFirstName());
22
            user.setLastName(model.getLastName());
23
            user.setMobile(model.getMobile());
24
            user.setEmail(model.getEmail());
25
            User savedUser = userRepository.save(user);
26
            if(userRepository.findById(savedUser.getId()).isPresent())
27
            return ResponseEntity.ok("User Created Successfully");
28
            else return ResponseEntity.unprocessableEntity().body("Failed Creating User as Specified");
29
        }
30
 
          
31
    }
32
}
33
 
          


Here, we are defining a method createUser that takes in model of type UserModel .

What we do is we create the new User. We get the values from the model object and will assign it to the new user we have created. First, we will start by checking whether the email is already present. If it is present I am using the  ResponseEntity class to return "email is already present."

ResponseEntity has many handy methods, so that you can format your return types. You can control anything that goes into the response: status code, headers, and body. Here we are setting the body of the response. 

After assigning the values to the new User, I am using the save method given by the  JpaRepository . The  Save method returns a User Object and I am assigning it to  savedUser. In the next line of code I check if it is present. It is to make doubly sure that the user has been saved. If it is present it will return that the user has been created successfully; otherwise I will get a failure message.

User Model Class

Java
 




xxxxxxxxxx
1
41


 
1
package com.notyfyd.model;
2
 
          
3
public class UserModel {
4
    private String firstName;
5
    private String lastName;
6
    private String mobile;
7
    private String email;
8
 
          
9
    public String getFirstName() {
10
        return firstName;
11
    }
12
 
          
13
    public void setFirstName(String firstName) {
14
        this.firstName = firstName;
15
    }
16
 
          
17
    public String getLastName() {
18
        return lastName;
19
    }
20
 
          
21
    public void setLastName(String lastName) {
22
        this.lastName = lastName;
23
    }
24
 
          
25
    public String getMobile() {
26
        return mobile;
27
    }
28
 
          
29
    public void setMobile(String mobile) {
30
        this.mobile = mobile;
31
    }
32
 
          
33
    public String getEmail() {
34
        return email;
35
    }
36
 
          
37
    public void setEmail(String email) {
38
        this.email = email;
39
    }
40
}
41
 
          



We use this model class for data binding. You can see how it is used in the controller. 

Using Model Class is one way of doing things. It separates the presentation concerns and persistent concerns. It is not mandatory in all cases. In this I am using a model class so we get an understanding and awareness of how it can be used.

User Controller

Java
 




xxxxxxxxxx
1
19


 
1
package com.notyfyd.controller;
2
 
          
3
import com.notyfyd.model.UserModel;
4
import com.notyfyd.service.UserService;
5
import org.springframework.beans.factory.annotation.Autowired;
6
import org.springframework.http.ResponseEntity;
7
import org.springframework.web.bind.annotation.PostMapping;
8
import org.springframework.web.bind.annotation.RequestBody;
9
import org.springframework.web.bind.annotation.RestController;
10
 
          
11
@RestController
12
public class UserController {
13
    @Autowired
14
    private UserService userService;
15
    @PostMapping("/user/create")
16
    public ResponseEntity<Object> createUser(@RequestBody UserModel model) {
17
        return userService.createUser(model);
18
    }
19
}



Here I am  autowiring the service class with the  @Autowired  annotation. We use the @PostMapping annotation for all the post request from the rest clients. 

We will use the Request body to pass in the data of type UserModel. This annotations are handy for binding requests with a domain object, in our case, the UserModel.

application.properties

Properties files
 




xxxxxxxxxx
1
13
9


1
server.port=2003
2
spring.datasource.driver-class-name= org.postgresql.Driver
3
spring.datasource.url= jdbc:postgresql://192.168.64.6:30432/jpa-test
4
spring.datasource.username = postgres
5
spring.datasource.password = root
6
spring.jpa.show-sql=true
7
spring.jpa.hibernate.ddl-auto=create



Now let's run the application. First, open Postman.

My JSON object creates an User.

JSON
 




xxxxxxxxxx
1


 
1
{
2
    "firstName": "Hello",
3
    "lastName": "World",
4
    "mobile":"9876538427",
5
    "email": "hello@mail.com"
6
}


Creating a user

Creating a user



Once you click send, you can see that the user is created in the database.

Please find the source code here.

You can find the video tutorials below.

Topics:
cloud ,java ,jpa ,microservices ,spring boot ,spring data jpa ,spring security ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}