我有一个简单的Spring启动应用程序,它使用H2内存数据库并试图初始化数据。
这是我的application.config:
#Database connection
spring.datasource.url=jdbc:h2:mem:practice_db
spring.datasource.username=sa
spring.datasource.password=123456
spring.datasource.driverClassName=org.h2.Driver
#spring.datasource.initialize=true
#spring.datasource.schema=schema.sql
#spring.datasource.data=schema.sql
#Hibernate configuration
#spring.jpa.hibernate.ddl-auto = none
schema.sql文件
CREATE TABLE IF NOT EXISTS `Person` (
`id` INTEGER PRIMARY KEY AUTO_INCREMENT,
`first_name` VARCHAR(50) NOT NULL,
`age` INTEGER NOT NULL
);
INSERT INTO `Person` (`first_name`, `age`) VALUES ('Peter', 20);
和data.sql
INSERT INTO `Person` (`first_name`, `age`) VALUES ('John', 20);
这是我的实体
/**
* Dummy data model.
* Just for test
*/
@Entity
@Table(name = "Person")
public class Person {
@Id
@GeneratedValue
@Column(name = "Id")
private Long id;
/**
* For hibernate
*/
@Version
private Integer version;
/**
* Person name
*/
@Basic(optional = false)
@Column(name = "first_name")
private String name;
/**
* Age. Primitive type can't be nullable
*/
@Basic(optional = false)
@Column(name = "age")
private int age;
表'人'是成功创建的。但它没有数据,尽管脚本已执行:
09:06:29.711 5823 [main] INFO o.s.j.datasource.init.ScriptUtils - Executing SQL script from URL [file:/C:/Users/User/Desktop/students/materials/practice/target/classes/schema.sql]
09:06:29.732 5844 [main] INFO o.s.j.datasource.init.ScriptUtils - Executed SQL script from URL [file:/C:/Users/User/Desktop/students/materials/practice/target/classes/schema.sql] in 21 ms.
09:06:29.742 5854 [main] INFO o.s.j.datasource.init.ScriptUtils - Executing SQL script from URL [file:/C:/Users/User/Desktop/students/materials/practice/target/classes/data.sql]
09:06:29.748 5860 [main] INFO o.s.j.datasource.init.ScriptUtils - Executed SQL script from URL [file:/C:/Users/User/Desktop/students/materials/practice/target/classes/data.sql] in 1 ms.
09:06:29.915 6027 [main] INFO o.s.o.j.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default'
09:06:29.949 6061 [main] INFO o.h.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [
当应用程序运行时,从该表中写入和读取数据工作正常。
如何在应用程序启动时初始化数据?
答案 0 :(得分:2)
根据Spring文档,Hibernate具有以下默认值:
spring.jpa.hibernate.ddl-auto= # DDL mode
。这实际上是hibernate.hbm2ddl.auto
属性的快捷方式。使用嵌入式数据库时默认为create-drop
,否则为“无”。
因此,对于嵌入式数据库,启动SQL脚本,然后Hibernate删除数据库并根据您的模型重新创建模式。因此,您不再看到插入内容。
作为解决方案,您只需在application.properties中设置spring.jpa.hibernate.ddl-auto=none
。