Spring+Mybatis整合的两种方式
Spring+Mybatis整合
引言
MyBatis框架开发:环境搭建(依赖、创建数据库连接) >> 建表 >> 实体类 >> 接口 >> 代理接口(SQL) >> 测试
spring+MyBatis框架开发:环境搭建(依赖、spring-mybatis.XML(创建连接、sqlSessionFactory、sqlSession)) >> 建表 >> 实体类 >> 接口 >> 代理接口(SQL) >> 接口实现类(获取SqlSession) >> 测试
Spring+Mybatis整合的两种方式区别:
- SqlSessionTemplate方式:sqlSessionFactory、sqlSession全部由配置文件创建,再通过接口实现类获取sqlsession
- SqlSessionDaoSuppory方式:sqlSessionFactory由配置文件创建,接口实现类通过继承SqlSessionDaoSupport来getSqlSession。
SqlSessionTemplate方式
-
搭建环境
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.4</version> </dependency> <!-- Spring操作数据库还需要一个spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.4</version> </dependency> <!-- AOC织入包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!-- lombok包 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.18</version> </dependency>lombok包常用注解
@Data 类自动获取get、set方法(常用)
@NoArgsConstructor 空参构造方法
@AllArgsConstructor 全参构造方法
@ToString 生成toString方法
@Value 把所有成员变量默认定义为private final修饰,并且不会生成set方法。
@Log4j 提供一个 属性名为log 的 log4j 日志对象 -
建表
oiling | CREATE TABLE `oiling` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(10) DEFAULT NULL, `pwd` varchar(15) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 -
创建表对应的实体类
package com.sheep.pojo; import lombok.Data; @Data public class Oiling{ private int id; private String name; private String pwd; } -
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> <!-- 不需要任何配置 --> </configuration> -
spring-mybatis.XML
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- DataSource:使用Spring的数据源替换MyBatis的配置。我们这里使用spring提供的jdbc --> <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/user01?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=true"/> <property name="username" value="root"/> <property name="password" value="123321"/> </bean> <!-- sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource"/> <!-- 绑定MyBatis配置文件(可添加,也可不添加)--> <property name="configLocation" value="classpath:config.XML"/> <property name="mapperLocations" value="classpath:com/sheep/mapper/*.XML"/> </bean> <!-- SqlSessionTemplate = sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!-- 只能使用构造器注入sqlSessionFactory,应为他没有set方法 --> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!-- 注册Bean --> <bean id="oilingMapper" class="com.sheep.mapper.OilingMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> </beans> -
创建接口
package com.sheep.mapper; import com.sheep.pojo.Oiling; import java.util.List; public interface OilingMapper { //查询所有 public List<Oiling> selectOiling(); } -
代理接口
<?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.sheep.mapper.OilingMapper"> <select id="selectOiling" resultType="com.sheep.pojo.Oiling"> select * from oiling; </select> </mapper> -
创建接口实现类
package com.sheep.mapper; import com.sheep.pojo.Oiling; import org.mybatis.spring.SqlSessionTemplate; import java.util.List; /** *我们的所有操作,都是用sqlSession来执行,但是整合spring之后使用SqlSessionTemplate; * */ public class OilingMapperImpl implements OilingMapper { //使用SqlSessionTemplate相当于sqlSession private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } public List<Oiling> selectOiling() { OilingMapper mapper = sqlSession.getMapper(OilingMapper.class); return mapper.selectOiling(); } } -
将接口实现类交给IoC容器
<!-- 注册Bean --> <bean id="oilingMapper" class="com.sheep.mapper.OilingMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> -
测试
import com.sheep.mapper.OilingMapper; import com.sheep.pojo.Oiling; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test2 { @Test public void test(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-dao.XML"); OilingMapper mapper = applicationContext.getBean("oilingMapper", OilingMapper.class); for (Oiling oiling:mapper.selectOiling()){ System.out.println(oiling); } } }
SqlSessionDaoSuppory方式
-
环境
dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.4</version> </dependency> <!-- Spring操作数据库还需要一个spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.4</version> </dependency> <!-- AOC织入包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!-- lombok包 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.18</version> </dependency> -
表
oiling | CREATE TABLE `oiling` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(10) DEFAULT NULL, `pwd` varchar(15) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 -
实体类
package com.sheep.pojo; import lombok.Data; @Data public class Oiling{ private int id; private String name; private String pwd; } -
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> <!-- 不需要任何配置 --> </confiation> -
spring-mybatis.XML
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- DataSource:使用Spring的数据源替换MyBatis的配置。我们这里使用spring提供的jdbc --> <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/user01?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=true"/> <property name="username" value="root"/> <property name="password" value="123321"/> </bean> <!-- sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource"/> <!-- 绑定MyBatis配置文件(可添加,也可不添加)--> <property name="configLocation" value="classpath:config.XML"/> <property name="mapperLocations" value="classpath:com/sheep/mapper/*.XML"/> </bean> <!-- 不需要在配置文件中创建sqlSession --> <!-- <!– SqlSessionTemplate = sqlSession –>--> <!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">--> <!-- <!– 只能使用构造器注入sqlSessionFactory,应为他没有set方法 –>--> <!-- <constructor-arg index="0" ref="sqlSessionFactory"/>--> <!-- </bean>--> <!-- 注册Bean --> <bean id="oilingMapperImpl2" class="com.sheep.mapper.OilingMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans> -
创建接口
package com.sheep.mapper; import com.sheep.pojo.Oiling; import java.util.List; public interface OilingMapper { //查询所有 public List<Oiling> selectOiling(); } -
代理接口
<?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.sheep.mapper.OilingMapper"> <select id="selectOiling" resultType="com.sheep.pojo.Oiling"> select * from oiling; </select> </mapper> -
创建接口实现类
package com.sheep.mapper; import com.sheep.pojo.Oiling; import org.mybatis.spring.support.SqlSessionDaoSupport; import java.util.List; public class OilingMapperImpl2 extends SqlSessionDaoSupport implements OilingMapper { @Override public List<Oiling> selectOiling() { return getSqlSession().getMapper(OilingMapper.class).selectOiling(); } } -
将接口实现类交给IoC容器
<bean id="oilingMapperImpl2" class="com.sheep.mapper.OilingMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> -
测试
import com.sheep.mapper.OilingMapper; import com.sheep.pojo.Oiling; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test2 { @Test public void test(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-dao.XML"); OilingMapper mapper = applicationContext.getBean("oilingMapperImpl2", OilingMapper.class); for (Oiling oiling:mapper.selectOiling()){ System.out.println(oiling); } } }
Spring事务声明
引言
事务必须服从ACID原则,即原子性(atomicity)、一致性(consistency)、隔离性(isolation)、持久性(durability)可理解为,事务其实就是一系列指令的集合。
- 原子性:操作这些指令时,要么全部执行成功,要么全部不执行,只要其中一个指令执行失败,所有的指令都执行失败,数据进行回滚,回到执行指令前的数据状态。
- 一致性:事务的执行数据从一个状态转换为另一个状态,但对于整个数据的完整性保持稳定。
- 隔离性:在该事务的执行过程中,无论发生任何数据的改变都应该只存在该事务中,对于外界不存在让任何影响。只有在事务确定正确提交之后,才会显示该事务对数据的改变。其他事务才能获取到这些改变后的数据。
- 持久性:当事务正确完成后它对于数据的改变是永久性的。
spring中的事务管理
-
在mybatis-spring.XML中添加事务管理
<!-- 配置声明式事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <constructor-arg ref="datasource"/> </bean> <!-- 结合AOP实现事务织入 --> <!-- 1、配置事务通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 给那些方法配置事务 --> <!-- 配置事务的传播特性 new propagation--> <tx:attributes> <tx:method name="add" propagation="REQUIRED"/> <tx:method name="delete" propagation="REQUIRED"/> <tx:method name="update" propagation="REQUIRED"/> <tx:method name="query" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置事务切入 --> <aop:config> <aop:pointcut id="txPointCut" expression="execution(* com.sheep.mapper.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config>
还历史以真诚,还生命以过程。 ——余秋雨
浙公网安备 33010602011771号