如何在Spring Boot应用启动时自动初始化H2数据库中的表?
时间: 2024-10-26 14:03:07 浏览: 15
Spring Boot+Mybatis集成H2数据库示例
在Spring Boot应用中,可以使用Spring Data JPA或者JDBC来自动初始化H2数据库中的表。这里我们以Spring Data JPA为例说明:
1. 首先,在你的项目中添加Spring Data JPA依赖到`pom.xml` 或 `build.gradle` 文件中。
2. 创建一个实体类(Entity),例如`Product.java`:
```java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
// ...其他字段和getter/setter
}
```
3. 创建一个配置类,如`DatabaseConfig.java`,配置数据源和JPA:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
@Configuration
@EnableJpaRepositories(basePackages = "com.example.demo.repository")
public class DatabaseConfig {
private static final String DATABASE_NAME = "spring_boot";
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan("com.example.demo.entity");
factoryBean.setJpaVendorAdapter(vendorAdapter);
return factoryBean;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:" + DATABASE_NAME + ";DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
dataSource.setUsername("sa"); // 使用H2默认的空用户名
dataSource.setPassword(""); // H2使用空密码
return dataSource;
}
}
```
4. 确保在`application.properties`或`application.yml`中启用JPA并设置H2作为数据源:
```properties
spring.datasource.url=jdbc:h2:mem:spring_boot;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update // 表会自动创建或更新,若需要仅创建则设为create
```
5. 当应用启动时,Spring会自动检测到`entityManagerFactory()`和`dataSource()`的bean,并在应用运行过程中管理数据访问。
阅读全文