Java Spring Boot with JPA CRUD Operation

Hello everyone, here is an example Java Spring Boot application with JPA CRUD operations:

// Import required libraries
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import javax.persistence.*;
import java.util.List;

// Define entity class
@Entity
@Table(name = "users")
class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

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

    // Default constructor required by JPA
    public User() {}

    // Constructor with parameters
    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    // Getters and setters
    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

// Define repository interface
interface UserRepository extends JpaRepository<User, Long> {}

// Define REST controller
@RestController
@RequestMapping("/api/users")
class UserController {
    @Autowired
    private UserRepository repository;

    // Create user
    @PostMapping("/")
    public User createUser(@RequestBody User user) {
        return repository.save(user);
    }

    // Read user by ID
    @GetMapping("/{id}")
    public User readUser(@PathVariable Long id) {
        return repository.findById(id).orElse(null);
    }

    // Read all users
    @GetMapping("/")
    public List<User> readAllUsers() {
        return repository.findAll();
    }

    // Update user by ID
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        return repository.save(user);
    }

    // Delete user by ID
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        repository.deleteById(id);
    }
}

// Define main class
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Here is an explanation of the code:
  • • The User class is defined as a JPA entity with three properties: id, name, and email. It has a default constructor and a constructor that takes name and email as parameters. It also has getters and setters for each property.
  • • The UserRepository interface extends JpaRepository and defines no additional methods. This allows it to inherit all of the CRUD operations from the JpaRepository interface.
  • • The UserController class defines five endpoints: createUser, readUser, readAllUsers, updateUser, and deleteUser. Each endpoint is mapped to a specific HTTP method and URL pattern using annotations. The createUser endpoint takes a User object in the request body and saves it to the database. The readUser endpoint takes an id parameter in the URL and returns the corresponding User object from the database. The readAllUsers endpoint returns a list of all User objects in the database. The updateUser endpoint takes an id parameter in the URL and a User object in the request body, updates the corresponding User object in the database, and returns the updated User object. The deleteUser endpoint takes an id parameter in


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext