三、spring整合MyBatis
官方下载地址
视频观看地址
https://www.bilibili.com/vide...
将 MyBatis 与 Spring 进行整合,主要解决的问题就是将SqlSessionFactory 对象交由 Spring来管理
只需要将 SqlSessionFactory 的对象生成器 SqlSessionFactoryBean 注册在 Spring 容器中,再将其注入给 Dao 的实现类即可完成整合
整合思路
需要有需要有Dao接口的代理对象,例如studentDao需要一个他的代理对象,使用SqlSession.getMapper(StudentDao.class),得到dao代理对象
需要有SqlSessionFactory,创建一个SqlSessionFactory对象,使用SqlSessionFactory.open()得到SqlSession对象
数据源DataSource对象,使用连接池对象替换mybatis自己的PooledDataSource
3.1 maven依赖
maven依赖
junit
junit
4.11
test
org.springframework
spring-context
5.2.5.RELEASE
org.springframework
spring-tx
5.3.8
org.springframework
spring-jdbc
5.3.8
org.mybatis
mybatis
3.5.7
org.mybatis
mybatis-spring
2.0.6
mysql
mysql-connector-java
8.0.25
com.alibaba
druid
1.2.1
org.projectlombok
lombok
1.18.20
src/main/java
**/*.properties
**/*.xml
false
3.2 实体类
定义实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer id;
private String name;
private String email;
private Integer age;
}
3.3 Dao接口与mapper文件
Dao接口
public interface StudentDao {
int insertStudent(Student student);
List selectStudentList();
}
mapper文件
insert into student values (#{id},#{name},#{email},#{age})
3.4 service接口与实现类
service接口
public interface StudentService {
int addStudent(Student student);
List queryAllStudents();
}
service实现类
@Service("myStudentService")
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public int addStudent(Student student) {
int result = studentDao.insertStudent(student);
return result;
}
@Override
public List queryAllStudents() {
List students = studentDao.selectStudentList();
return students;
}
}
3.5 MyBatis主配置文件
主配置文件中不再需要数据源的配置了,因为数据源要交给 Spring 容器来管理了
这里对 mapper 映射文件的注册,使用
3.6 spring的配置文件
- jdbc.properties文件
- jdbc.driver=com.mysql.cj.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/mybatis01?serverTimezone=Asia/Shanghai
- jdbc.username=root
- jdbc.password=123456
该属性文件若要被 Spring 配置文件读取,其必须在配置文件中进行注册。使用
注册 SqlSessionFactoryBean
定义 Mapper 扫描配置器 MapperScannerConfigurer
Mapper 扫描配置器 MapperScannerConfigurer会自动生成指定的基本包中 mapper 的代理对象 。该 Bean无需设置 id 属性。basePackage 使用分号或逗号设置多个包
3.7 向service注入接口名
向 Service 注入 Mapper 代理对象时需要注意,由于通过 Mapper 扫描配置器MapperScannerConfigurer生成的 Mapper 代理对象没有名称,所以在向 Service 注入 Mapper代理时,无法通过名称注入。但可通过接口的简单类名注入,因为生成的是这个 Dao 接口的对象。
全部配置文件