我是靠谱客的博主 诚心玫瑰,最近开发中收集的这篇文章主要介绍Springboot-H2DB,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

为什么在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

 

转载于:https://www.cnblogs.com/luffystory/p/11160847.html

最后

以上就是诚心玫瑰为你收集整理的Springboot-H2DB的全部内容,希望文章能够帮你解决Springboot-H2DB所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(114)

评论列表共有 0 条评论

立即
投稿
返回
顶部