本文主要是介绍SpringBoot集成H2数据库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1)添加H2的依赖
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>compile</scope>
</dependency>
2)添加连接配置,启用web控制台
spring:datasource:url: jdbc:h2:~/usersdriver-class-name: org.h2.Driverusername: root #随便定义password: 123456 #随便定义h2:console:path: /h2-console #h2嵌入式数据库控制台enabled: true
3)初始化数据库的表结构
/*** 嵌入式数据库h2*/
@Slf4j
@Configuration
//DataSource创建完后才初始化此类
@AutoConfigureAfter(DataSource.class)
public class H2DataSourceConfig {//初始化sqlprivate static final String schema="classpath:db/schema-h2.sql";@AutowiredDataSource dataSource;@AutowiredApplicationContext applicationContext;@PostConstructpublic void init() throws Exception {//初始化本地数据库String userHome= System.getProperty("user.home");//获取系统用户目录File f = new File(userHome+File.separator+"h2.lck");if(!f.exists()){log.info("--------------初始化h2数据----------------------");f.createNewFile();Resource resource= applicationContext.getResource(schema);ScriptUtils.executeSqlScript(dataSource.getConnection(),resource);}else{log.info("--------------h2数据库已经存在----------------------");}}
}
sql语句:
DROP TABLE IF EXISTS tb_user;
CREATE TABLE tb_user
(id BIGINT NOT NULL COMMENT 'id',name VARCHAR(30) COMMENT '姓名',PRIMARY KEY (id)
);
insert into tb_user(id,name)values(1, 'zhangsan');
insert into tb_user(id,name)values(2, 'lisi');
insert into tb_user(id,name)values(3, 'wangwu');
4)测试-应用程序
@SpringBootApplication
public class H2Application implements ApplicationRunner {public static void main(String[] args) {SpringApplication.run(H2Application.class, args);}@AutowiredJdbcTemplate jdbcTemplate;@Overridepublic void run(ApplicationArguments args) throws Exception {jdbcTemplate.query("select * from tb_user", new RowCallbackHandler() {@Overridepublic void processRow(ResultSet resultSet) throws SQLException {String id = resultSet.getString("id");String name = resultSet.getString("name");log.info("id:{}, name:{}", id, name);}});}
}
5)测试-web控制台
输入配置文件中设置的用户名和密码登录:
在web控制台种可以做增删改查:
完整的源码下载:https://github.com/xjs1919/enumdemo下面的h2-demo
这篇关于SpringBoot集成H2数据库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!