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

Spring Boot kết nối MySQL localhost như thế nào

Cấu hình trong application.properties:

spring.datasource.username=tenDangNhapMySQL
spring.datasource.password=matKhauMySQL
spring.datasource.url=jdbc:mysql://localhost:3306/tenCoSoDuLieu
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Tạo bảng demo71 để kiểm tra:

mysql> CREATE TABLE demo71 (
    -> id INT,
    -> name VARCHAR(20)
    -> );

Chèn dữ liệu:

mysql> INSERT INTO demo71 VALUES(100,'John');
mysql> INSERT INTO demo71 VALUES(101,'David');
mysql> INSERT INTO demo71 VALUES(102,'Bob');

Hiển thị:

mysql> SELECT * FROM demo71;
+------+-------+
| id   | name  |
+------+-------+
| 100  | John  |
| 101  | David |
| 102  | Bob   |
+------+-------+

Để kiểm tra, viết ứng dụng Spring Boot:

Controller:

@RestController
@RequestMapping("/table")
public class TableController {
    @Autowired
    EntityManager entityManager;

    @GetMapping("/demo71")
    public String getData() {
        Query sqlQuery = entityManager.createNativeQuery("SELECT name FROM demo71");
        List result = sqlQuery.getResultList();
        StringBuilder sb = new StringBuilder();
        for (String s : result) {
            sb.append(s).append(" ");
        }
        return sb.toString();
    }
}

Main class:

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

Chạy ứng dụng và truy cập URL: https://localhost:8093/table/demo71 sẽ trả về: John David Bob.