Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Cấu hình DataSource trong Spring Boot (application.properties) cho MySQL

Giới thiệu

Lỗi Failed to configure a DataSource trong Spring Boot thường do thiếu cấu hình kết nối database trong application.properties. Cần cung cấp đủ: URL, username, password, driver class.

Cấu hình application.properties

spring.datasource.username=yourUserName
spring.datasource.password=yourPassword
spring.datasource.url=jdbc:mysql://localhost:3306/yourDatabase?useSSL=false&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Ví dụ Controller Spring Boot

@RestController
@RequestMapping("/users")
public class DisplayController {
    @Autowired
    EntityManager entityManager;

    @GetMapping("/getdata")
    public String getAll() {
        Query query = entityManager.createNativeQuery("SELECT first_name FROM demo25");
        List allData = query.getResultList();
        return allData.toString();
    }
}

Chạy ứng dụng

  1. Tạo bảng demo25 và chèn dữ liệu trong MySQL.
  2. Chạy class main @SpringBootApplication.
  3. Truy cập: https://localhost:port/users/getdata.

Lưu ý: Driver class com.mysql.cj.jdbc.Driver dành cho MySQL Connector/J 8.0+. Phiên bản cũ dùng com.mysql.jdbc.Driver. Tham số useSSL=false&serverTimezone=UTC tránh warning phổ biến.