1)添加H2的依赖
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>compile</scope>
</dependency>
2)添加连接配置,启用web控制台
spring:
datasource:
url: jdbc:h2:~/users
driver-class-name: org.h2.Driver
username: root #随便定义
password: 123456 #随便定义
h2:
console:
path: /h2-console #h2嵌入式数据库控制台
enabled: true
3)初始化数据库的表结构
/**
* 嵌入式数据库h2
*/
@Slf4j
@Configuration
//DataSource创建完后才初始化此类
@AutoConfigureAfter(DataSource.class)
public class H2DataSourceConfig {
//初始化sql
private static final String schema="classpath:db/schema-h2.sql";
@Autowired
DataSource dataSource;
@Autowired
ApplicationContext applicationContext;
@PostConstruct
public 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);
}
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public void run(ApplicationArguments args) throws Exception {
jdbcTemplate.query("select * from tb_user", new RowCallbackHandler() {
@Override
public 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