How to implement CRUD operations in Spring Boot with JPA?

Implementing CRUD operations in Spring Boot using JPA is very straightforward. Here are some basic steps:

Configure database connection: Set up database connection information, including database URL, username, and password, in the `application.properties` or `application.yml` file.

Create entity class: generate a class that corresponds to a database table and annotate it with `@Entity`. You can set the primary key attributes using `@Id` and `@GeneratedValue` annotations.

Create a Data Access Object (DAO): Create an interface that extends `JpaRepository`, where T is the type of entity class and ID is the type of the primary key. This interface will automatically provide basic CRUD methods.

Write business logic code: Inject DAO objects in the service class and write corresponding business methods to handle specific CRUD operations.

Invoke methods to perform operations: Call methods from the service class in the controller or any other needed place to carry out the corresponding create, read, update, or delete operations.

Below is a simple example demonstrating how to implement CRUD operations using Spring Boot and JPA.

Configure database connection information:

spring:

  datasource:

    url: jdbc:mysql://localhost:3306/mydatabase

    username: root

    password: password

Create entity class:

@Entity

public class User {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    private String name;

    private int age;

    // 省略构造函数、getter和setter方法

}

3. Establishing Data Access Objects (DAO):

@Repository

public interface UserRepository extends JpaRepository<User, Long> {

    // 可以自定义一些查询方法

    List<User> findByAgeGreaterThan(int age);

}

Write the business logic code.

@Service

public class UserService {

    @Autowired

    private UserRepository userRepository;

    public User findById(Long id) {

        return userRepository.findById(id).orElse(null);

    }

    public List<User> findByAgeGreaterThan(int age) {

        return userRepository.findByAgeGreaterThan(age);

    }

    public User save(User user) {

        return userRepository.save(user);

    }

    public void deleteById(Long id) {

        userRepository.deleteById(id);

    }

}

5. Invoke methods for operation:

@RestController

public class UserController {

    @Autowired

    private UserService userService;

    @GetMapping("/users/{id}")

    public User getUserById(@PathVariable Long id) {

        return userService.findById(id);

    }

    @PostMapping("/users")

    public User createUser(@RequestBody User user) {

        return userService.save(user);

    }

    @DeleteMapping("/users/{id}")

    public void deleteUserById(@PathVariable Long id) {

        userService.deleteById(id);

    }

}

This is just a basic example that you can further expand and optimize according to your needs.

bannerAds