SpringBoot集成內(nèi)存數(shù)據(jù)庫H2的實踐
目標
在SpringBoot中集成內(nèi)存數(shù)據(jù)庫H2.
為什么
像H2、hsqldb、derby、sqlite這樣的內(nèi)存數(shù)據(jù)庫,小巧可愛,做小型服務(wù)端演示程序,非常好用。最大特點就是不需要你另外安裝一個數(shù)據(jù)庫。
操作步驟
修改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
添加初始化數(shù)據(jù)文件
建表腳本:schema.sql
CREATE TABLE `blog` ( `id` int AUTO_INCREMENT NOT NULL, `title` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) );
導(dǎo)入數(shù)據(jù)腳本: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();
}
數(shù)據(jù)bean:Blog
@Data
public class Blog {
private int id;
private String title;
}
工程截圖

運行
運行HspApplication即可
效果

完整源代碼
https://gitee.com/hspbc/springboot_memdb
到此這篇關(guān)于SpringBoot集成內(nèi)存數(shù)據(jù)庫H2的實踐的文章就介紹到這了,更多相關(guān)SpringBoot集成H2內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何使用axis調(diào)用WebService及Java?WebService調(diào)用工具類
Axis是一個基于Java的Web服務(wù)框架,可以用來調(diào)用Web服務(wù)接口,下面這篇文章主要給大家介紹了關(guān)于如何使用axis調(diào)用WebService及Java?WebService調(diào)用工具類的相關(guān)資料,需要的朋友可以參考下2023-04-04
SpringBoot+MQTT+apollo實現(xiàn)訂閱發(fā)布功能的示例
這篇文章主要介紹了SpringBoot+MQTT+apollo實現(xiàn)訂閱發(fā)布功能的示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
Java創(chuàng)建多線程的幾種方式實現(xiàn)
這篇文章主要介紹了Java創(chuàng)建多線程的幾種方式實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
確保SpringBoot定時任務(wù)只執(zhí)行一次的常見方法小結(jié)
在Spring Boot項目中,確保定時任務(wù)只執(zhí)行一次是一個常見的需求,這種需求可以通過多種方式來實現(xiàn),以下是一些常見的方法,它們各具特點,可以根據(jù)項目的實際需求來選擇最合適的方法,需要的朋友可以參考下2024-10-10

