如何在SpringBoot2启动时自动创建表、插入数据
一、springboot2中如何根据实体类自动生成表
只需在类上添加@Entity注解。spring boot启动时会自动生成user表(当然,数据库还得自己先创建)
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
/**
* @author chushiyan
* @email Y2h1c2hpeWFuMDQxNUAxNjMuY29t(base64)
* @description
*/
@Data
@Entity
public class User implements Serializable {
@Id
private String id;
private String name;
}
对应的application.yml:
server:
port: 10000
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8
username: root
password: root
jpa:
database: MySQL
show-sql: true
generate-ddl: true
二、springboot2启动时如何向数据库自动插入数据
1、首先,在resources目录下创建data.sql文件,例如:
INSERT INTO user (id,name) VALUES ('0','chushiyan');
INSERT INTO user (id,name) VALUES ('1','zhangsan');
INSERT INTO user (id,name) VALUES ('2','lisi');
INSERT INTO user (id,name) VALUES ('3','wangwu');
springboot启动时,会从classpath下读取该文件,用来向数据库的表插入数据。
2、然后,配置
spring.jpa.hibernate.ddl-auto=create-drop # 或者create
spring.datasource.initialization-mode=always
注:spring.jpa.hibernate.ddl-auto=create 或者 create-drop会先删除已存在的表,主要用于测试。
完整application.yml:
server:
port: 10000
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8
username: root
password: root
initialization-mode: always
jpa:
database: MySQL
show-sql: true
generate-ddl: true
hibernate:
ddl-auto: create-drop
三、如何让SpringBoot2根据我们自定义的建表语句创建数据库表
1、首先,在resources目录下创建schema.sql文件,例如:
CREATE TABLE user (
id VARCHAR(128) NOT NULL ,
name VARCHAR(32) NOT NULL,
PRIMARY KEY (id)
);
springboot启动时,会从classpath下读取该文件,用来创建数据库表。
2、然后,配置:
spring.jpa.hibernate.ddl-auto=none
完整application.yml:
server:
port: 10000
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8
username: root
password: root
initialization-mode: always
jpa:
database: MySQL
show-sql: true
generate-ddl: true
hibernate:
ddl-auto: none
验证是否使用了schema.sql文件创建表,查询数据库:
mysql> show create table user;
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------+
| user | CREATE TABLE `user` (
`id` varchar(128) NOT NULL,
`name` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
mysql>
网友评论