本文代码地址:https://github.com/hawkingfoo/java-web
上一节中,我们分享了SpringBoot快速整合Mybits的方法。本节中我们将在web项目中引入H2数据库相关的操作。即SpringBoot通过整合MyBatis访问H2数据库。
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.5.10.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.47version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.36version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.h2databasegroupId>
<artifactId>h2artifactId>
<scope>testscope>
dependency>
dependencies>
在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;
这里我们需要创建4个类,第一个是SpringBoot的启动类,在test目录下创建。
- 创建SpringBoot启动类
@SpringBootApplication
@EnableAutoConfiguration
public class ApplicationTest {
public static void main(String[] args) {
SpringApplication.run(ApplicationTest.class, args);
}
}
public class Student implements Serializable {
private int id;
private String name;
private int sex; // 0=male, 1=female
private String addr;
}
这里需要注意的是,属性的名字要和数据库中的名字保持一致。
@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 studentList = studentMapper.selectAll();
Assert.assertEquals(1, studentList.size());
}
}