目录
目标
为什么
操作步骤工程截图运行
效果总结
目标
在SpringBoot中集成内存数据库hsqldb.
为什么
像H2、hsqldb、derby、sqlite这样的内存数据库,小巧可爱,做小型服务端演示程序,非常好用。最大特点就是不需要你另外安装一个数据库。
操作步骤
修改pom.xml文件
<dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> </dependency>
修改项目配置文件application.yml
spring: datasource: username: hsp password: 123456 url: jdbc:hsqldb:mem://localhost/blogdb;shutdown=true driver-class-name: org.hsqldb.jdbcDriver schema: classpath:schema.sql data: classpath:data.sql initialization-mode: always continue-on-error: true
添加初始化数据文件
建表脚本:schema.sql
CREATE TABLE blog ( id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY, title varchar(255) DEFAULT NULL, );
导入数据脚本: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; }
工程截图
运行
运行HspApplication即可
效果
总结
1.当前的hsqldb在配置的时候一定要在url中添加shutdown=true;否者会出现错误:
org.hsqldb.HsqlException: user lacks privilege or object not found: USER(表不存在的错误)
2.当前的hsqldb中的实体类只需要@Entity注解,@Id和@GeneratedValue
3.dao层需要继承jpa的或者reposity即可
完整源代码
https://gitee.com/hspbc/springboot_memdb
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)