当前位置:首页 > 通信资讯 > 正文

springboot使用h2数据库(spring h2数据库)

目标

在SpringBoot中集成内存数据库H2.

为什么

像H2、hsqldb、derby、sqlite这样的内存数据库,小巧可爱,做小型服务端演示程序,非常好用。最大特点就是不需要你另外安装一个数据库。

操作步骤

修改pom.xml文件

<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>

修改项目配置文件application.yml

spring: datasource: username: hsp password: 123456 url: jdbc:h2:file:./blogDB driver-class-name: org.h2.Driver schema: classpath:schema.sql data: classpath:data.sql initialization-mode: always continue-on-error: true h2: console: enabled: true path: /h2

添加初始化数据文件

建表脚本:schema.sql

CREATE TABLE `blog` ( `id` int AUTO_INCREMENT NOT NULL, `title` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) );

导入数据脚本:data.sql

insert into blog(id,title) values(1,'花生皮编程博客');

启动类:HspApplication

@MapperScan({"cn.hsp.blog"}) @SpringBootApplication public class HspApplication { public static void main(String[] args) { SpringApplication.run(HspApplication.class, args); } }

Controller类:BlogController

@RestController @RequestMapping("/blog") public class BlogController { @Autowired private BlogMapper blogMapper; @GetMapping(value="/query") public List<Blog> query() { return blogMapper.query(); } }

Mapper类:BlogMapper

@Repository public interface BlogMapper { @Select(value = "select * from blog") List<Blog> query(); }

数据bean:Blog

@Data public class Blog { private int id; private String title; }

工程截图

springboot使用h2数据库(spring h2数据库)

运行

运行HspApplication即可

效果

springboot使用h2数据库(spring h2数据库)

完整源代码

https://gitee.com/hspbc/springboot_memdb

到此这篇关于SpringBoot集成内存数据库H2的实践的文章就介绍到这了,更多相关SpringBoot集成H2内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.cn/post/7004788724072448036

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。