一 导入依赖
<!--整合mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
二 编写配置文件
appliction.yml中添加如下配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
mybatis:
mapper-locations: classpath:mybatis/*.xml
type-aliases-package: com.msb.pojo
mapper-locations: classpath:mybatis/*.xml mapper映射文件包扫描
type-aliases-package:实体类别名包扫描
三 编写功能代码
1.在启动类上添加注解@MapperScan("com.msb.mapper"),表示mapper接口所在位置
@SpringBootApplication
@MapperScan("com.msb.mapper")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class,args);
}
2 .定义mapper接口
如果不在MyApplication启动类上添加@MapperScan必须在UserMapper接口上添加@Mapper注解。
//@Mapper
public interface UserMapper {
List<User> selectAll();
}
3 定义mapper.xml映射文件
在resource下新建mybatis文件夹,mapper.xml文件名没有要求了,不需要和接口名完全对应了,是根据namespace去找接口。但是最好还是和接口名字保持一致
4 .controller层代码
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
@ResponseBody
public List<User> findAll(){
return userService.findAll();
}
}
5.service层代码
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
}
6. idea中往往会误报代码错误,如果我们确定代码无问题,可以通过降低idea检查代码的严格程度来消除报错
快捷键: ctrl+alt+shift+h