Springboot集成Mybatis
1、导入依赖
<!--Mybatis对应的starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--数据库连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
2、创建数据库表格
drop table if exists `student`;
create table if not exists `student` (
id int primary key ,
name varchar(20),
age int,
sex varchar(5)
)engine=innodb charset=utf8;
insert into student (id, name, age, sex) value (1, "test1", 1, "男");
insert into student (id, name, age, sex) value (2, "test2", 2, "男");
insert into student (id, name, age, sex) value (3, "test3", 3, "女");
insert into student (id, name, age, sex) value (4, "test4", 4, "女");
select * from student;
3、创建对应的Dao
public class Student {
private Integer id;
private String name;
private Integer age;
private String sex;
//getter and setter...
}
4、建立MVC层
建立service层、mapper(dao)层和controller层,实现简单的查询所有学生方法
controller:
@RestController
public class StudentController {
@Resource
StudentService studentService;
@GetMapping("/api/all")
public List<Student> getAllStudent() {
return studentService.getAllStudent();
}
}
service:
public interface StudentService {
public List<Student> getAllStudent();
}
serviceImpl:
@Service
public class StudentServiceImpl implements StudentService {
@Resource
StudentMapper studentMapper;
@Override
public List<Student> getAllStudent() {
return studentMapper.getAllStudent();
}
}
mapper:
@Repository
public interface StudentMapper {
public List<Student> getAllStudent();
}
5、在application.yml中配置mybatis
在yml中配置type-aliases-package时,由于Mybatis-plugin识别不到,会报红,看着不爽,所以改为在核心配置文件中配置别名
mybatis:
#mybatis核心配置文件
config-location: classpath:config/mybatis-config.xml
#配置mapper映射文件
mapper-locations: classpath:mapper/*.xml
#配置数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: root
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="cn.jyu.mybatisdemo.mapper"/>
</typeAliases>
</configuration>
6、Mapper映射文件
<?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="cn.jyu.mybatisdemo.mapper.StudentMapper">
<select id="getAllStudent" resultType="Student">
select * from student;
</select>
</mapper>
7、启动
在启动类中添加MapperScan注解,扫描Mapper接口,启动即可
注意点: Service注解要加在接口实现类上,不然报错