Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การตั้งค่า DataSource ใน Spring Boot สำหรับ MySQL

การกำหนดค่า DataSource ใน application.properties

Spring Boot ตั้งค่า DataSource อัตโนมัติจาก properties ใน application.properties หรือ application.yml

Properties ที่จำเป็น

spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

โครงสร้างโปรเจกต์ Spring Boot

  • Main Class: @SpringBootApplication
  • Controller: @RestController, @RequestMapping
  • ใช้ EntityManager สำหรับ Native Query

ตัวอย่าง Controller

@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();
    }
}

การรันและทดสอบ

  1. Run Main Class as Java Application
  2. เข้าถึง: https://localhost:port/users/getdata

ตารางตัวอย่าง

CREATE TABLE demo25 (first_name VARCHAR(20));
INSERT INTO demo25 VALUES ('David'), ('Adam'), ('Chris');

หมายเหตุ: ใช้ Driver Class ใหม่ com.mysql.cj.jdbc.Driver (MySQL 8+) และควรเพิ่ม ?useSSL=false&serverTimezone=UTC ใน URL