[SpringBoot] Using JPA in SpringBoot for database operations

In Spring Boot, using JPA for database operations usually requires the following steps:

1. Add dependencies

Add the Spring Data JPA dependency in the pom.xml file:


```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
```


2. Configure data source

Configure data source information in the application.properties or application.yml file:


```
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8mb4
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
```


3. Create entity class

Use JPA annotations to create entity classes and specify mapping relationships with database tables:


```java
@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "username")
    private String username;
    @Column(name = "password")
    private String password;
    // getters and setters
}
```


4. Create Repository interface

Create the Repository interface and annotate it with JPA annotations:


```java
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByUsername(String username);
}
```


5. Create Service class

Create a Service class, inject into Repository and implement related business logic:


```java
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    public List<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
}
```

Guess you like

Origin blog.csdn.net/wenhuakulv2008/article/details/134273129