为什么在Springboot中用H2DB
用Springboot开发需要连接数据库的程序的时候,使用H2DB作为内存数据库可以很方便的调试程序。
怎么用
1.加入依赖
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
2.创建实体类,并指明表的名称,这个实体类是放在src/main/java 下的,注意,这个实体类是应用程序会用到的,不是为了测试而写的。不用我们先CreateDB,再在DB下create 一个 Table,H2DB根据实体类会帮我们create 好Table 放在H2DB里面。
package com.springboot.h2; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "T_CUSTOMER") public class Customer { @Id @Column(name = "customer_id") private Long customerId; @Column(name = "customer_name") private String customerName; public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String toString() { return String.format("Customer id: %d ,Customer name: %s", customerId, customerName); } }
3.在src/test/resource 下面放置 准备测试数据的SQL文件
4.此时,开始写测试类
package com.springboot.h2; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = {Application.class}) public class H2DBTest { @Autowired private CustomerRepository repository; @Test public void getAllCustomerTest() { List<Customer> customers = repository.findAll(); for(Customer c : customers) { System.out.println(c); } } }
当run测试类的H2DB 会首先执行放在 src/test/resource 下面的SQL文件,准备好测试数据。
在 @Test 方法里就可以测试程序的逻辑了。
源码如下,请笑纳 :)
https://github.com/XLuffyStory/springboot-h2DB-test