Spring Boot Database Access Tutorial

In Spring Boot, accessing database data is typically done using Spring Data JPA. Below is a simple example:

Firstly, import the Spring Data JPA dependency in the pom.xml file.

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

Configure the database connection information in the application.properties file.

spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Create a class, for example User.

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

    private String username;
    private String email;

    // getters and setters
}

Create a Repository interface that extends JpaRepository.

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    // 可以在这里定义一些自定义的查询方法
}

Inject the UserRepository in the Service class and call the relevant methods.

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    public User saveUser(User user) {
        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

With this, you can access database data through UserService. And of course, by calling UserService in the Controller, you can operate on the database data.

bannerAds