【附源码】Spring Boot实战系列——一、配置内存数据库H2
【附源码】Spring Boot实战系列——二、配置多个数据源(H2数据库)
【附源码】Spring Boot实战系列——三、配置多个数据源(Mysql数据库)
【附源码】Spring Boot实战系列——四、日志管理
【附源码】Spring Boot实战系列——五、事务抽象
【附源码】Spring Boot实战系列——六、货币存数据库的处理
引入H2依赖
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
创建表和数据
H2数据库启动时,默认会执行资源文件夹下的schema.sql和data.sql
schema.sql
create table foo(id int identity, value varchar(64));
data.sql
insert into foo(id, value) values(1, 'one');
insert into foo(id, value) values(2, 'two');
核心代码
* 查看数据库连接信息
* 查看表的数据
@SpringBootApplication
@Slf4j
public class SpringDemoApplication implements CommandLineRunner {
@Autowired
private DataSource dataSource;
@Autowired
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
showConnection();
showData();
}
/**
* 打印数据库连接信息
* @throws Exception
*/
private void showConnection() throws Exception{
log.info("dataSource=" +dataSource.toString());
Connection conn = dataSource.getConnection();
log.info("Connection=" + conn.toString());
conn.close();
}
/**
* 展示数据
*/
private void showData(){
jdbcTemplate
.queryForList("select * from foo")
.forEach(row -> log.info(row.toString()));