我有一個簡單的彈簧啓動應用程序與H2內存數據庫,並試圖initalize數據。爲什麼Hibernate不初始化數據?
這是我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 [
當應用程序正在運行時,從該表中寫入和讀取數據時工作正常。
如何初始化應用程序啓動數據?
可能的重複https://stackoverflow.com/questions/38040572/spring-boot-loading-initial-data – Afridi
@Afridi我沒有PersonRepository。我用EntityManager.persist將數據保存在應用程序中。 g00glen00b sais他需要使用INSERT語句的data.sql文件。我有這樣的文件,但由於某種原因它不起作用 – Kirill