SpringBoot + MySQL + MyBatis 实操示例教学
一、准备工作
1.导入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.配置文件application.yml
server:
port: 8088
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 1234
mybatis:
mapper-locations: classpath:mapper/*xml
type-aliases-package: com.example.domain.po
这里的mapper-locations设置的是mapper映射的xml文件位置:
如果不设置的话,调用数据库的数据就会报错:
二、示例代码
controller:
EmployeeController示例:
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private IEmployeeService employeeService;
@GetMapping("/getData")
public List<Employee> getEmployeeList(){
List<Employee> employeeList = employeeService.getData();
System.out.println(employeeList);
return employeeList;
}
}
service:
IEmployeeServcie接口:
public interface IEmployeeService {
List<Employee> getData();
}
impl:
EmployeeServiceImpl实现IEmployeeServcie接口:
@Service
public class EmplyeeServiceImpl implements IEmployeeService {
@Autowired
private EmployeeDao employeeDao;
@Override
public List<Employee> getData() {
return employeeDao.getData();
}
}
dao:
@Mapper
public interface EmployeeDao {
List<Employee> getData();
}
resources/mapper:
EmployeeMapper.xml:
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.EmployeeDao">
<resultMap id="employeeResultMap" type="com.example.domain.po.Employee">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="salary" column="salary"/>
<result property="entryTime" column="entry_time"/>
</resultMap>
<select id="getData" resultMap="employeeResultMap">
select id,name,age,salary,entry_time
from employee
</select>
</mapper>
mapper:
namespace:对应的是dao中的EmployeeDao文件
select:
id :对应的的是EmployeeDao文件方法名
resultMap:是返回的结果是列表
type:是列表的类型数据,案例中列表的类型数据是Employee
下图有更完整的解读:
进行测试:
测试方式一(直接访问浏览器):
http://localhost:8088/employee/getData
测试方式二(使用测试工具Postman):