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

เชื่อมต่อ Spring Boot กับ Local MySQL ผ่าน application.properties

การตั้งค่า application.properties

spring.datasource.username=yourMySQLUserName
spring.datasource.password=yourMySQLPassword
spring.datasource.url=jdbc:mysql://localhost:3306/yourDatabaseName
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

คำอธิบายแต่ละ Property

Propertyคำอธิบายตัวอย่าง
usernameMySQL Usernameroot
passwordMySQL Password123456
urlJDBC URL: host, port, databasejdbc:mysql://localhost:3306/sampledatabase
driver-class-nameJDBC Driver Class (MySQL 8.0+)com.mysql.cj.jdbc.Driver

ตัวอย่างตารางทดสอบ

CREATE TABLE demo71 (id INT, name VARCHAR(20));
INSERT INTO demo71 VALUES (100,'John'), (101,'David'), (102,'Bob');

Spring Boot Application: Controller

@RestController
@RequestMapping("/table")
public class TableController {
    
    @Autowired
    EntityManager entityManager;
    
    @GetMapping("/demo71")
    @ResponseBody
    public String getData() {
        Query sqlQuery = entityManager.createNativeQuery("SELECT name FROM demo71");
        List<String> result = sqlQuery.getResultList();
        
        StringBuilder sb = new StringBuilder();
        for (String name : result) {
            sb.append(name).append(" ");
        }
        return sb.toString().trim();
    }
}

Main Class

@SpringBootApplication
public class JavaMysqlDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(JavaMysqlDemoApplication.class, args);
    }
}

Dependency (pom.xml / build.gradle)



    mysql
    mysql-connector-j
    8.0.33


    org.springframework.boot
    spring-boot-starter-data-jpa



implementation 'mysql:mysql-connector-j:8.0.33'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

รันและทดสอบ

  1. Run As → Java Application (Main Class)
  2. เข้าถึง: https://localhost:8093/table/demo71
  3. ผลลัพธ์: John David Bob

การตั้งค่าเพิ่มเติม (แนะนำ)

# Connection Pool (HikariCP - Default)
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=30000

# JPA/Hibernate
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

# Timezone
spring.datasource.url=jdbc:mysql://localhost:3306/yourDatabaseName?serverTimezone=Asia/Bangkok

Troubleshooting

Errorสาเหตุแก้ไข
Communications link failureMySQL ไม่รัน / Port ผิด / Firewallตรวจสอบ service, port 3306, bind-address
Access denied for userUser/Pass ผิด / Host ไม่ได้อนุญาตGRANT, FLUSH PRIVILEGES, check host %
Unknown databaseDatabase ไม่มีอยู่CREATE DATABASE หรือแก้ URL
Driver class not foundขาด DependencyAdd mysql-connector-j
Public Key Retrieval is not allowedMySQL 8.0 Authenticationเพิ่ม allowPublicKeyRetrieval=true ใน URL