1.首先看下一下maven的依赖,主要是mybatis依赖,mysql驱动,以及之后测试使用的依赖spring-boot-test
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
mysql
mysql-connector-java
org.junit.jupiter
junit-jupiter-api
org.springframework
spring-test
5.1.2.RELEASE
compile
junit
junit
4.12
org.springframework.boot
spring-boot-test
2.其次在application.properties文件中配置mybatis的mapper文件位置,和实体类的包路径,还有最好加上驼峰命名规范
####mybatis配置
# 注意注意
mybatis.mapper-locations=classpath:edu/hohai/chapter1/gt/mapper/*.xml
#mybatis.mapper-locations=classpath:mapper/*.xml #这种方式需要自己在resources目录下创建mapper目录然后存放xml
mybatis.type-aliases-package=edu.hohai.chapter1.gt.entity
# 驼峰命名规范 如:数据库字段是 order_id 那么 实体字段就要写成 orderId
mybatis.configuration.map-underscore-to-camel-case=true
看下项目结构:这里我把Mapper类和Mapper映射文件放在了一起,这时候我们还需要做下面设置,让springboot能在java包中扫描xml文件(springboot默认扫描的是包中的*.java文件),如果使用resources目录下面的xml,这打开上面的
mybatis.mapper-locations=classpath:mapper/*.xml
项目结构图
3.设置springboot在包中扫描xml文件
org.springframework.boot
spring-boot-maven-plugin
true
src/main/resources
src/main/java
**/*.xml
true
4.UserMapper.java UserMapper.xml
package edu.hohai.chapter1.gt.mapper;
import edu.hohai.chapter1.gt.entity.User;
import org.apache.ibatis.annotations.Mapper;
/**
* @author cronous
* @create 2018-11-01 15:04
*/
@Mapper //注意这里的Mapper注解
public interface UserMapper {
int insert(User user);
}
INSERT INTO `t_user`(`username`,`password`) VALUES (#{username},#{password})
5.数据库表
CREATE TABLE `t_user` (
`id` int(8) NOT NULL AUTO_INCREMENT COMMENT '主键自增',
`username` varchar(50) NOT NULL COMMENT '用户名',
`password` varchar(50) NOT NULL COMMENT '密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='用户表';
6.测试
package edu.hohai.chapter1;
import edu.hohai.chapter1.gt.entity.User;
import edu.hohai.chapter1.gt.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author cronous
* @create 2018-11-01 15:20
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ChapterTest {
private static final Logger log = LoggerFactory.getLogger(ChapterTest.class);
@Autowired
private UserMapper userMapper;
@Test
public void test1() throws Exception {
final int row1 = userMapper.insert(new User("u1", "p1"));
log.info("[添加结果] - [{}]", row1);
final int row2 = userMapper.insert(new User("u2", "p2"));
log.info("[添加结果] - [{}]", row2);
final int row3 = userMapper.insert(new User("u1", "p3"));
log.info("[添加结果] - [{}]", row3);
}
}
7.查看数据库
发现已经写入数据库,测试完成