h2是一个轻量级的内存数据库,配置简单,启动速度快。
springboot默认配置好了h2的配置信息,我们直接使用h2数据库即可
<!-- jar依赖的版本控制,需要导入springboot的parent依赖 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 对数据库操作的依赖 -->
<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>
该POJO在程序启动时会生成对应的表
@Entity
public class User {
@Id
@GeneratedValue
private long id;
private String title;
private String content;
public User(String title, String content) {
this.title = title;
this.content = content;
}
public User() {
super();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
UserRepository 无需实现,CrudRepository提供了基本的增删改查的方法了
public interface UserRepository extends CrudRepository<User, Long> {
}
运行的时候h2数据库才存在,可以对数据库进行操作
(如果想在容器启动的时候执行sql文件,使用jdbc:initialize-database,用法 百度)
@RestController
public class HelloController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/save")
public String save(){
userRepository.save(new User("title1", "content1"));
userRepository.save(new User("title2", "content2"));
userRepository.save(new User("title3", "content3"));
userRepository.save(new User("title4", "content4"));
userRepository.save(new User("title5", "content5"));
userRepository.save(new User("title6", "content6"));
return "save ok";
}
@RequestMapping("/findAll")
public Iterable<User> findAll(){
return userRepository.findAll();
}
}
application.yml可以不配置,也可以正常使用h2数据库
这儿的配置,主要是为了对数据进行持久化处理(存入文件中),否则应用重启,数据丢失
spring:
datasource:
url: jdbc:h2:file:~/.h2/testdb # ~ 对应 C:\Users\administrator 用户目录
username: sa
password: sa
driverClassName: org.h2.Driver
jpa:
hibernate:
ddl-auto: update #如果数据库没有对应的表则创建,有则更新
持久化生成的文件