Springboot通过JPA(Hibernate)框架集成H2数据库 (Springboot 2.7.6 java 8)
pom文件引入如下依赖:
<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>
以上2个是核心依赖,另外为了使的程序运行,还需要其他依赖,主要有:
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
application文件定义
spring:
application:
name: demoH2
datasource: #数据库配置
url: jdbc:h2:~/mydb
driver-class-name: org.h2.Driver
username: root
password: test
h2: #控制台配置
console:
path: /h2-console
enabled: true
jpa: #jpa配置
hibernate:
ddl-auto: update
show-sql: true
接下来是程序主体内容,目录如下:
定义数据实体,也就是H2数据库中表的结构
@Entity
@Data
@Table(name = "DBGirl")
public class DBGirl {
@Id
@GeneratedValue
private Long id;
private String name;
private Long age;
private Long grade;
}
定义JPA服务接口
public interface MyRepository extends JpaRepository<DBGirl, Long> {
}
Controller定义
@RestController
@Slf4j
public class GirlController {
@Autowired
MyRepository myRepository;
@PostMapping(value = "/girl")
public void add(@RequestBody DBGirl girl) {
myRepository.save(girl);
log.info("An entity is added successfully");
}
@RequestMapping(value = "/girl", method = RequestMethod.GET)
public String say(@RequestParam(value = "name", required = false) String name) {
return myRepository.findAll().toString();
}
}
H2内存数据库使用教程详解 - 大江东去的文章 - 知乎
https://zhuanlan.zhihu.com/p/509877891