Spring整合Mybatis
Spring整合MyBatis 是将Spring和MyBatis应用到一个项目中
MyBatis 提供数据库相关的操作,完成对象数据和关系数据的转换
Spring完成项目的管理,通过IOC和AOP完成依赖注入,事务管理等操作
导入依赖
<!--spring上下文核心包-->
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.26</version>
</dependency><!--mybatis核心包-->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.9</version>
</dependency><!--mybatis类型支持包-->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis-typehandlers-jsr310</artifactId><version>1.0.2</version>
</dependency><!--mysql驱动包-->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version>
</dependency><!--mybatis整合spring支持包-->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.7</version>
</dependency><!--spring事务管理器-->
<dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.3.26</version>
</dependency><!--spring对JDBC支持包-->
<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.26</version>
</dependency><!--alibaba连接池产品-->
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.9</version>
</dependency><!--测试 整合框架-->
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.9.0</version><scope>test</scope>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.3.26</version><scope>test</scope>
</dependency>
创建实体类
public class StudentBean {private Integer id;private String name;private String gender;private LocalDate birthday;private String tel;private Double grade;
}
创建业务接口和mapper接口
public interface IStudentService {List<StudentBean> findAll();void add(StudentBean studentBean);
}
@Mapper //表示mapper接口
public interface IStudentMapper {List<StudentBean> findAll();void add(StudentBean studentBean);
}
导入配置文件
1.mybatis主配置文件
<?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><!--配置日志,可以打印执行的sql语句--><settings><setting name="logImpl" value="STDOUT_LOGGING" /></settings><!--允许使用指定包中的类名作为别名--><typeAliases><package name="com.project.bean"/></typeAliases>
</configuration>
2.mapper文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace为命名空间,设置为mapper接口全路径,表示为连接接口中方法,提供sql语句-->
<mapper namespace="com.project.mapper.mapper接口名"></mapper>
配置类
@Configuration
@ComponentScan("com.project")
@MapperScan("com.project.mapper")
@EnableTransactionManagement
public class MyBatisConfig {@Bean public DataSource getDataSource(){//连接池对象 获取连接DruidDataSource dataSource = new DruidDataSource();//连接驱动dataSource.setDriverClassName("com.mysql.jdbc.Driver");dataSource.setUrl("jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf8&allowMultiQueries=true");dataSource.setUsername("root");dataSource.setPassword("0618");//连接数量dataSource.setMaxActive(100);dataSource.setMinIdle(10);// 设置 最大连接等待时间 超过时间 返回nulldataSource.setMaxWait(2000);return dataSource;}@Beanpublic SqlSessionFactoryBean getFactory(){//得到会话工厂SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();//获取数据源factoryBean.setDataSource(this.getDataSource());//加载mybatis主配置文件factoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));return factoryBean;}@Beanpublic TransactionManager transactionManager(DataSource data){DataSourceTransactionManager manager = new DataSourceTransactionManager();manager.setDataSource(data);return manager;}
}
注解
@Configuration 标识该类为配置类
@ComponentScan("com.project") 扫描指定包及子包中 带spring注解的组件,如(@Component、@Service、@Controller、@Repository ),并将它们自动注册为 Spring Bean【但不能扫描接口】
@MapperScan("com.project.mapper")
Mapper 接口不能被 @ComponentScan 扫描到并注册为 Spring Bean。如果要让 Mapper 接口成为 Spring Bean,需要使用 @Mapper 注解标记该接口,然后在 Spring 配置类中使用 @MapperScan 注解扫描 Mapper 接口所在的包,将其注册为 Spring Bean。这样,在应用程序中就可以使用 @Autowired 注解将 Mapper 接口注入到其他组件中使用。
@EnableTransactionManagement 提供事务支持
在一个 Spring 应用程序中,如果需要对一些操作进行事务管理,就需要使用 @Transactional 注解来标记需要进行事务管理的方法。但是,仅仅使用 @Transactional 注解是不够的,还需要使用 @EnableTransactionManagement 注解来开启 Spring 的事务管理器功能。
@EnableTransactionManagement 注解告诉 Spring 启动事务管理器,并将其应用到带有 @Transactional 注解的方法上
@Bean
在 Spring 中,@Bean 注解用于声明一个方法返回一个 bean 实例。在配置类中使用 @Bean 注解声明一个方法时,Spring 容器会在初始化时调用该方法,并将方法返回的对象添加到容器中作为一个 bean。
方法
1、配置数据源
获取 Druid 数据源,并使用 @Bean 注解将其声明为 Spring 组件。
在该方法中,首先创建一个 DruidDataSource 对象,并设置了连接字符串、用户名、密码、连接池大小等参数。然后,将该数据源对象返回。
由于使用了 @Bean 注解,该方法返回的数据源对象将被 Spring 容器管理,并可以在其他组件中使用 @Autowired 注解注入该数据源对象,从而使用该数据源对象来创建 JDBC 连接对象,访问数据库。
2、配置会话工厂
获取 MyBatis 的 SqlSessionFactoryBean 工厂的方法,并使用 @Bean 注解将其声明为 Spring 组件。
在该方法中,首先创建了一个 SqlSessionFactoryBean 工厂对象,并设置了数据源和 MyBatis 主配置文件的位置。
通过调用 this.getDataSource() 方法获取数据源对象,并将其设置到 SqlSessionFactoryBean 工厂中。然后,通过调用 factoryBean.setConfigLocation 方法设置 MyBatis 主配置文件的位置,这里是使用 ClassPathResource 加载类路径下的 mybatis.cfg.xml 文件。最后,将该工厂对象返回。
由于使用了 @Bean 注解,该方法返回的 SqlSessionFactoryBean 工厂对象将被 Spring 容器管理,并可以在其他组件中使用 @Autowired 注解注入该对象,从而使用该对象来创建 MyBatis 的 SqlSession 对象,访问数据库。
3、配置事务管理器
获取事务管理器 DataSourceTransactionManager 的方法,并使用 @Bean 注解将其声明为 Spring 组件。
在该方法中,需要传入一个数据源对象,该数据源对象可以通过 @Autowired 注解注入到该方法中。
在方法中,首先创建了一个 DataSourceTransactionManager 对象,并使用传入的数据源对象设置其数据源属性。然后,将该事务管理器对象返回。
由于使用了 @Bean 注解,该方法返回的事务管理器对象将被 Spring 容器管理,并可以在其他组件中使用 @Autowired 注解注入该对象,从而使用该对象来管理事务,保证事务的一致性和完整性。
完成业务接口实现类
@Service //扫描 业务
@Transactional // 实现类的所有方法 都支持事务管理
public class StudentServiceImp implements IStudentService {@Autowired //通过该注解 将 IStudentMapper 接口的实例注入到该类中private IStudentMapper mapper;@Overridepublic List<StudentBean> findAll() {return mapper.findAll();}public void add(StudentBean studentBean) {mapper.add(studentBean);}
}
@Autowired
它可以自动地将一个对象注入到另一个对象中,从而完成依赖注入。
当一个类中的某个属性被标记为@Autowired时,Spring框架会自动查找匹配的对象,并将其注入到该属性中。这样,我们就不需要手动创建对象了,Spring框架会自动帮我们完成依赖注入。
测试
@ExtendWith(SpringExtension.class)// JUnit 5 的注解
@ContextConfiguration(classes = MyBatisConfig.class)//加载配置类
public class MyTest {@Autowired //通过该注解将 IStudentService 接口的实例注入到该测试类中,从而可以使用该接口中定义的方法进行测试。private IStudentService service;@Testpublic void MyTest(){StudentBean stu = new StudentBean("BroRiver","男", LocalDate.parse("2000-05-20"),"1335061",90.5);service.add(stu);System.out.println(service.findAll());}
}
@ContextConfiguration
它的作用是加载 MyBatisConfig 类,该类中包含了 MyBatis 和 Spring 的整合配置信息,比如:
-
将 MyBatis 的配置文件和 mapper 接口的 XML 文件注入到 Spring 容器中,以便 MyBatis 能够访问和使用这些文件。
-
将 MyBatis 的 mapper 接口和 Spring 的 bean 进行关联,使得 MyBatis 能够在运行时调用 mapper 接口的方法,从而实现对数据库的访问。
-
配置 MyBatis 与 Spring 的整合,使得 MyBatis 能够通过 Spring 的事务管理器来管理事务,从而保证数据库操作的一致性和完整性。