springboot h2数据库例子
时间: 2024-08-24 15:00:28 浏览: 38
Spring Boot 和 H2 数据库结合是一个常见的轻量级开发场景,H2 是一个内存型的嵌入式数据库,常用于快速原型开发和测试。下面是一个简单的 Spring Boot 应用使用 H2 的例子:
首先,在 `pom.xml` 文件中添加 H2 数据源依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope> <!-- 只在运行时添加 -->
</dependency>
</dependencies>
```
然后,配置数据源和 JPA 配置:
```java
@Configuration
@EnableJpaRepositories(basePackages = "com.example.demo.repository") // 指定仓库模块位置
public class DatabaseConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2) // 使用H2
.addScript("schema.sql") // 加载初始化脚本
.build();
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new JpaTransactionManager(entityManagerFactory(dataSource));
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
Map<String, Object> jpaProperties = new HashMap<>();
jpaProperties.put("hibernate.dialect", H2Dialect.class);
jpaProperties.put("hibernate.show_sql", true); // 显示SQL日志
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource);
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.example.demo.entity"); // 扫描实体类包
factory.setJpaProperties(jpaProperties);
return factory;
}
}
```
在这个例子中,你需要创建一个 `schema.sql` 脚本来定义数据库结构。现在你可以创建一个简单的实体类 (`User.java`),并创建对应的 Repository 接口 (`UserRepository.java`)。