前言:本文通过简单介绍Spring Boot和MyBatis框架整合,提升与数据库的交互作用,同时也解决了多表多条件分页查询问题,该组合会比SSM简单好用。
设计数据库
DROP TABLE IF EXISTS `department`;
SET character_set_client = utf8mb4 ;
CREATE TABLE `department` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`dname` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `springboot_demo`.`department` (`id`, `dname`)
VALUES (101, '教学部'),
(102, '市场部'),
(103, '教研部'),
(104, '运营部'),
(105, '后勤部');
导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
配置application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
mybatis:
type-aliases-package: com.kaung.pojo
mapper-locations: classpath:mapper/*.xml
创建实体类 pojo
Department
@Data
public class Department {
private Integer id;
private String dname;
}
创建mapper
DepartmentMapper.java
@Mapper
@Repository
public interface DepartmentMapper {
public List<Department> getDepartmentList();
public Department getDepartmentById(Integer id);
}
DepartmentMapper.xml
<?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.kaung.mapper.DepartmentMapper">
<select id="getDepartmentList" resultType="Department">
select * from department;
</select>
<select id="getDepartmentById" parameterType="int" resultType="Department">
select * from department where id = #{id};
</select>
</mapper>
创建service
DepartmentService
public interface DepartmentService {
public List<Department> getDepartmentList();
public Department getDepartmentById(Integer id);
}
DepartmentServiceImpl
@Service
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
DepartmentMapper departmentMapper;
@Override
public List<Department> getDepartmentList() {
return departmentMapper.getDepartmentList();
}
@Override
public Department getDepartmentById(Integer id) {
return departmentMapper.getDepartmentById(id);
}
}
创建controller
DepartmentController
@RestController
public class DepartmentController {
@Autowired
DepartmentService departmentService;
@GetMapping("/department")
public List<Department> getdepartmentList() {
List<Department> departmentList = departmentService.getDepartmentList();
return departmentList;
}
@GetMapping("/department/{id}")
public Department getdepartmentById(@PathVariable("id") Integer id) {
Department department = departmentService.getDepartmentById(id);
return department;
}
}
打印SQL日志
logging:
level:
com.kaung.mapper: debug
项目仓库
学习资料来源:
【狂神说Java】SpringBoot最新教程IDEA版通俗易懂
|