SpringBoot整合H2数据库
Spring Boot整合H2数据库的步骤如下:
- 在
pom.xml
中添加H2数据库的依赖:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
- 在
application.properties
或application.yml
中配置H2数据库:
# application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
或者使用YAML格式配置:
# application.yml
spring:
datasource:
url: jdbc:h2:mem:testdb
driverClassName: org.h2.Driver
username: sa
password:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
- 创建实体类和Repository接口:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 其他字段和方法
}
import org.springframework.data.jpa.repository.JpaRepository;
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
// 自定义查询方法
}
- 创建Service类和Controller类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyEntityService {
@Autowired
private MyEntityRepository repository;
// 业务逻辑方法
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyEntityController {
@Autowired
private MyEntityService service;
// 控制器方法
}
- 运行Spring Boot应用,H2数据库将在内存中运行,并可通过配置的Repository进行访问。
以上步骤提供了一个基本的示例,实际使用时需要根据具体需求添加更多的配置和代码。
评论已关闭