The target

Integrate the in-memory database H2 in SpringBoot.

why

In-memory databases such as H2, HSQLDB, Derby and SQLite are small and cute, making small server-side demos very useful. The biggest feature is that you don’t need to install another database.

steps

  1. Modify the POM.xml file
<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>
Copy the code
  1. Modify the project configuration file 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
Copy the code
  1. Add the initialization data file
  • Create table script: schema.sql
CREATE TABLE `blog` (
  `id` int AUTO_INCREMENT NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
Copy the code
  • Data import script: data.sql
Insert into blog(id,title) values(1,' 1 ');Copy the code
  1. Start class: HspApplication
@MapperScan({"cn.hsp.blog"})
@SpringBootApplication
public class HspApplication {

	public static void main(String[] args) {
		SpringApplication.run(HspApplication.class, args);
	}

}
Copy the code
  1. The Controller class: BlogController
@RestController @RequestMapping("/blog") public class BlogController { @Autowired private BlogMapper blogMapper; @GetMapping(value="/query") public List<Blog> query() { return blogMapper.query(); }}Copy the code
  1. The Mapper class: BlogMapper
@Repository
public interface BlogMapper {
    @Select(value = "select * from blog")
    List<Blog> query();
}
Copy the code
  1. Data beans: blogs
@Data
public class Blog {
    private int id;
    private String title;
}
Copy the code

Engineering screenshots

run

Run HspApplication

The effect

Complete source code

Gitee.com/hspbc/sprin…

About me

Xiamen university computer professional | huawei eight years senior engineer Ten years software development experience, 5 years experience in teaching programming training Currently engaged in the teaching of programming, software development, software class graduation design guidance. All programming materials and open source projects can be found at juejin.cn/post/700279…

Integrated in-memory database family

SpringBoot integrated memory database H2 SpringBoot integrated memory database Derby SpringBoot integrated memory database HSQLDB SpringBoot integrated memory database Sqlite