1. 程式人生 > >springboot整合H2記憶體資料庫,實現單元測試與資料庫無關性

springboot整合H2記憶體資料庫,實現單元測試與資料庫無關性

一、新建spring boot工程

image.png

新建工程的時候,需要加入JPA,H2依賴

二、工程結構

image.png

pom檔案依賴如下:


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
 
	<groupId>com.chhliu.springboot.h2</groupId>
	<artifactId>springboot-h2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
 
	<name>springboot-h2</name>
	<description>Demo project for Spring Boot H2</description>
 
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
 
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.7</java.version>
	</properties>
 
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
 
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
 
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

三、編寫實體類

package com.chhliu.springboot.h2.entity;
 
import java.math.BigDecimal;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
 
@Entity
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
 
  @Column
  private String username;
 
  @Column
  private String name;
 
  @Column
  private Short age;
 
  @Column
  private BigDecimal balance;
 
  ……省略gettter和setter方法
}

四、編寫dao


package com.chhliu.springboot.h2.repository;
 
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
 
import com.chhliu.springboot.h2.entity.User;
 
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
 
}

五、編寫controller


package com.chhliu.springboot.h2.controller;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
 
import com.chhliu.springboot.h2.entity.User;
import com.chhliu.springboot.h2.repository.UserRepository;
 
@RestController
public class UserController {
 
  @Autowired
  private UserRepository userRepository;
 
  @GetMapping("/user/{id}")// 注意,此處使用的是GetMapping註解,該註解的作用類似與@RequestMapping(value="/user/{id}" ,method=RequestMethod.GET),@PostMapping註解同理
  public User findById(@PathVariable Long id) {
    return this.userRepository.findOne(id);
  }
}

六、配置檔案

# 伺服器埠號
server.port=7900
# 是否生成ddl語句
spring.jpa.generate-ddl=false
# 是否列印sql語句
spring.jpa.show-sql=true
# 自動生成ddl,由於指定了具體的ddl,此處設定為none
spring.jpa.hibernate.ddl-auto=none
# 使用H2資料庫
spring.datasource.platform=h2
# 指定生成資料庫的schema檔案位置
spring.datasource.schema=classpath:schema.sql
# 指定插入資料庫語句的指令碼位置
spring.datasource.data=classpath:data.sql
# 配置日誌列印資訊
logging.level.root=INFO
logging.level.org.hibernate=INFO
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
logging.level.org.hibernate.type.descriptor.sql.BasicExtractor=TRACE
logging.level.com.itmuch=DEBUG

七、啟動程式

在瀏覽器中輸入如下URL:

http://localhost:7900/user/4

可以看到測試結果

{"id":4,"username":"user4","name":"馬六","age":20,"balance":100.00}

說明,我們的整合是OK的

八、測試dao層

package com.chhliu.springboot.h2;
 
import org.junit.Assert;
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;
 
import com.chhliu.springboot.h2.entity.User;
import com.chhliu.springboot.h2.repository.UserRepository;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootH2ApplicationTests {
 
	@Autowired
	private UserRepository repository;
	
	@Test
	public void test(){
		User u = repository.findOne(1L);
		Assert.assertEquals("成功的測試用例", "張三", u.getName());
	}
}

發現測試是ok的!

九、總結

由於H2是關係記憶體資料庫,當程式啟動的時候,會在記憶體中建立表,並將資料儲存在記憶體中,當重啟程式後,會自動刪除記憶體中的資料,從而可以很好的用來做dao層的單元測試和service層的單元測試,使整個程式不會依賴具體的資料庫,同時也提高了單