本文代碼地址:https://github.com/hawkingfoo/java-web
一、概述
上一節中,我們分享了SpringBoot快速整合Mybits的方法。本節中我們將在web項目中引入H2數據庫相關的操作。即SpringBoot通過整合MyBatis訪問H2數據庫。
二、快速整合H2
1、修改pom.xml,添加依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--測試相關依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、添加數據庫相關配置
在src/test/resources
目錄下,添加application.properties
文件。具體內容如下:
# mysql 驅動: h2
spring.datasource.driver-class-name=org.h2.Driver
# h2 內存數據庫 庫名: test
spring.datasource.url=jdbc:h2:mem:test
# 初始化數據表
spring.datasource.schema=classpath:init_table.sql
spring.datasource.username=
spring.datasource.password=
# 打印 SQL語句, Mapper所處的包
logging.level.com.hawkingfoo.dao=debug
在src/test/resources
目錄下,添加init_table.sql
文件。具體內容如下:
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(1024) NOT NULL,
`sex` tinyint(1) NOT NULL,
`addr` varchar(1024) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
3、添加其他代碼
這裏我們需要創建4個類,第一個是SpringBoot的啓動類,在test目錄下創建。
- 創建SpringBoot啓動類
@SpringBootApplication
@EnableAutoConfiguration
public class ApplicationTest {
public static void main(String[] args) {
SpringApplication.run(ApplicationTest.class, args);
}
}
- 創建一個Model類
public class Student implements Serializable {
private int id;
private String name;
private int sex; // 0=male, 1=female
private String addr;
}
這裏需要注意的是,屬性的名字要和數據庫中的名字保持一致。
- 創建一個Mapper類
@Component
@Mapper
public interface StudentMapper {
@Insert("INSERT INTO student (name, sex, addr) VALUES (#{name}, #{sex}, #{addr})")
int insert(Student stu);
}
- 創建一個測試類
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {ApplicationTest.class, DataSourceAutoConfiguration.class})
public class StudentMapperTest {
@Autowired
private StudentMapper studentMapper;
@Test
public void testInsert() {
Student stu = new Student("a", 0, "x");
studentMapper.insert(stu);
List<Student> studentList = studentMapper.selectAll();
Assert.assertEquals(1, studentList.size());
}
}