本文共 3868 字,大约阅读时间需要 12 分钟。
环境:
在IDEA中新建项目,选择Spring Initializr,选择下面的Spring Boot Starter:
在application.properties中配置:
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/test_db?serverTimezone=Asia/Shanghai&characterEncoding=UTF-8spring.datasource.username=springuserspring.datasource.password=test123
不加characterEncoding=UTF-8会导致读写数据库中文乱码
在MySQL数据库中创建下面的表:
CREATE TABLE `t_user` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `name` varchar(64) NOT NULL, `email` varchar(128) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
在IDEA Database中配置数据库连接,相关配置参见上面。
确保IDEA中已安装Free MyBatis Plugin。
在Database中打开数据库连接,找到t_user表,右键选择mybatis-generator。
在model setting中:
在dao setting中:
在xml mapper setting中:
点击OK按钮,开始生成代码如下:
@SpringBootApplication@MapperScan("me.cookcode.springboot.mybatisdemo.mapper")public class MybatisDemoApplication { public static void main(String[] args) { SpringApplication.run(MybatisDemoApplication.class, args); }}
@MapperScan类似Spring的@ComponentScan可以自动扫描和注入Mapper,就不用再在每个Mapper接口中声明为Mapper和Component。
在UserMapper.java中增加@Mapper
注解表明该接口为MyBatis Mapper接口,增加@Component
表明该接口为Spring组件。
@Mapper@Componentpublic interface UserMapper { int deleteByPrimaryKey(Long id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record);}
# 指定Mapper XML的类路径mybatis.mapperLocations=classpath:mapper/*Mapper.xml
注意:不配置mapperLocations会出现错误:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
注意:Mapper XML放在
src/main/resources/mapper/
下,而不是和Mapper类代码放在一起,在编译之后Mapper XML文件在target/classes/mapper
下。
Spring可以通过指定
classpath*:
与classpath:
前缀加路径的方式从classpath加载文件,如bean的定义文件。classpath*:
的出现是为了从多个jar文件中加载相同的文件。classpath:
只能加载找到的第一个文件。使用
classpath*
时需要特别注意会不会加载了其它不想加载的文件,尤其是使用**
路径通配符时。
MyBatis-Plus的mapper-locations的默认位置为:classpath*:/mapper/**/*.xml"
,因此如果将Mapper XML放在了/src/main/resources/mapper
目录(或其子目录)下,就不需要指定mybatis-plus.mapper-locations。
参见MyBatis-Pus的源代码MybatisPlusProperties.java的mapperLocations
编写一个RestController类来测试。
@RestControllerpublic class UserController { @Autowired private UserMapper userMapper; @PostMapping("/user") public int addUser(@RequestBody User user) { return userMapper.insertSelective(user); } @GetMapping("/user/{id}") public User getUser(@PathVariable("id") String id) { return userMapper.selectByPrimaryKey(Long.valueOf(id)); }}
在IDEA中安装Restful Toolkit插件,打开View / Tools / RestServices来查看定义的REST API。
在RestServices中找到/user
接口的RequestBody的内容,类似:
{ "id": 1, "name": "demoData", "email": "demoData", "serialVersionUID": 1}
去掉id和serialVersionUID,填入参数值,得到要测试的JSON:
{ "name": "小明", "email": "ming.xiao@cookcode.me"}
在RestServices中测试新增记录:PUT
http://localhost:8080/user
再测试查询记录:GET
http://localhost:8080/user/{id}
确保已安装MyBatis Log Plugin
打开Tools / MyBatis Log Plugin,查看可以直接执行的MyBatis SQL日志。
另外在Spring Boot中开启日志参考:
转载地址:http://vwkdf.baihongyu.com/