网络编程
位置:首页>> 网络编程>> 数据库>> SpringBoot集成内存数据库Derby的实践

SpringBoot集成内存数据库Derby的实践

作者:花生皮编程  发布时间:2024-01-13 06:02:42 

标签:SpringBoot,Derby
目录
  • 目标

  • 为什么

  • 操作步骤

  • 工程截图

  • 运行

  • 效果

目标

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

为什么

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

操作步骤

修改pom.xml文件


<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>

修改项目配置文件application.yml


spring:
 datasource:
   username: hsp
   password: 123456
   url: jdbc:derby:blogDb;create=true
   driver-class-name: org.apache.derby.jdbc.EmbeddedDriver
   schema: classpath:schema.sql
   data: classpath:data.sql
   initialization-mode: always
   continue-on-error: true

添加初始化数据文件

建表脚本:schema.sql


CREATE TABLE blog (
 id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
 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集成内存数据库Derby的实践

运行

运行HspApplication即可

效果

SpringBoot集成内存数据库Derby的实践

完整源代码

来源:https://juejin.cn/post/7004790994977849358

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com