文章目录
- 一、导入依赖
- 二、编写配置文件
- 三、在启动类上添加注解,表示mapper接口所在位置
- 四、定义mapper接口
- 五、定义mapper.xml映射文件
- 六、service层
- 七、controller层
- 八、修改idea检查代码的严格程度
一、导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
二、编写配置文件
server:
port: 8081
servlet:
context-path: /springboot1
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test1?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
mybatis:
# mapper映射文件包扫描
mapper-locations: classpath:/mappers/*.xml
# 实体类别名包扫描
type-aliases-package: com.buba.pojo
三、在启动类上添加注解,表示mapper接口所在位置
如果不在MyApplication启动类上添加@MapperScan必须在UserMapper接口上添加@Mapper注解。
@SpringBootApplication
//@MapperScan("com.buba.mappers")
public class ApplicationStarter {
public static void main(String[] args) {
SpringApplication.run(ApplicationStarter.class,args);
}
}
四、定义mapper接口
package com.buba.mappers;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author qlx
*/
@Mapper
public interface TestMapper {
List<String> selectNameAll();
}
五、定义mapper.xml映射文件
在resource下新建mappers文件夹,mapper.xml文件名没有要求了,不需要和接口名完全对应了,是根据namespace去找接口。但是最好还是和接口名字保持一致
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.buba.mappers.TestMapper">
<select id="selectNameAll" resultType="string">
select name from user
</select>
</mapper>
六、service层
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public List<String> selectNameAll() {
return testMapper.selectNameAll();
}
}
七、controller层
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/selectNameAll")
public List<String> selectNameAll() {
return testService.selectNameAll();
}
}
八、修改idea检查代码的严格程度
idea中往往会误报代码错误,如果我们确定代码无问题,可以通过降低idea检查代码的严格程度来消除报错
快捷键: ctrl+alt+shift+h