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

การสร้างตารางด้วย MySQL และ Hibernate

เพื่อสร้างตาราง คุณต้องเพิ่มบรรทัดต่อไปนี้ลงในไฟล์ application.properties:

spring.jpa.hibernate.ddl-auto=update

การตั้งค่านี้จะทำให้ Hibernate สร้างตาราง demo88 โดยอัตโนมัติ ตัวอย่างไฟล์ application.properties แบบเต็ม:

spring.datasource.platform=mysql
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
server.port=8191
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/sampledatabase
spring.datasource.username=root
spring.datasource.password=123456

ตัวอย่าง: Entity Class สำหรับสร้างคอลัมน์ตาราง

package com.automaticallytablecreation;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class demo88 {
    @Id
    private int id;
    
    @Column(name="name")
    private String name;
}

ตัวอย่าง: Main Class

package com.automaticallytablecreation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

คลิกขวาที่ Main Class แล้วเลือก Run as Java Application โปรแกรมจะรันและสร้างตารางโดยอัตโนมัติ

การตรวจสอบตารางที่สร้าง

mysql> show create table demo88;

ผลลัพธ์

+--------+------------------------------------------------------------+
| Table  | Create Table                                               |
+--------+------------------------------------------------------------+
| demo88 | CREATE TABLE `demo88` (
  `id` int NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+--------+-------------------------------------------------------------+
1 row in set (0.03 sec)