导入依赖
<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>
<version>1.18.12</version>
<scope>provided</scope>
</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在启动类上添加注解,表示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层代码
package com.msb.controller;
import com.msb.pojo.User;
import com.msb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
@ResponseBody
public List<User> findAll(){
return userService.findAll();
}
}
5 service层代码
package com.msb.service.impl;
import com.msb.pojo.User;
import com.msb.mapper.UserMapper;
import com.msb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
@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