1、Mybatis-Spring整合
官网:http://mybatis.org/spring/zh/index.html
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
创建映射器 mapper 和 SqlSession
并注入到 bean 中。
需要的版本对应:
-
首先看一下包的结构
-
在
pom.xml
文件中导入相应的依赖<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring02</artifactId> <groupId>com.jiang</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>spring04</artifactId> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.10.RELEASE</version> </dependency> <!--Spring jdbc(new)--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.10.RELEASE</version> </dependency> <!--aop aspectjweaver--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <!--mybatis-spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> </dependencies> <!-- 如果xml在java文件下,就要设置资源过滤--> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> </project>
-
编写
UserMapper
接口package com.jiang.mapper; import com.jiang.pojo.User; import java.util.List; public interface UserMapper { List<User> getUserList(); }
-
编写
User
实体类package com.jiang.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class User { private int id; private String name; private String pwd; }
-
编写
UserMapper.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"> <!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.jiang.mapper.UserMapper"> <!--select查询语句--> <select id="getUserList" resultType="com.jiang.pojo.User"> select * from mybatis.user </select> </mapper>
-
编写
applicationContext.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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--整合mybatis--> <!--1.数据源配置--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!--2.注入sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--别名--> <property name="typeAliases" value="com.jiang.pojo.User"/> <!--扫描包--> <property name="mapperLocations" value="classpath:com/jiang/xml/*.xml"/> </bean> <!--3.创建sqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!--4.放入bean--> <bean id="userMapperImpl" class="com.jiang.mapper.impl.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> </beans>
-
在
applicationContext.xml
编写第3步完成后,去编写UserMapper
接口的实现类UserMapperImpl
,最后在去做第4步package com.jiang.mapper.impl; import com.jiang.pojo.User; import com.jiang.mapper.UserMapper; import org.mybatis.spring.SqlSessionTemplate; import java.util.List; //实现类 public class UserMapperImpl implements UserMapper { //注入sqlSession: Spring管理了 private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } @Override public List<User> getUserList() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.getUserList(); } }
2、事务的控制
下面的所有操作基于上面操作都成功的前提下!
-
给
UserMapper
里增加添加用户和删除用户的方法package com.jiang.mapper; import com.jiang.pojo.User; import java.util.List; public interface UserMapper { List<User> getUserList(); //添加用户 int addUser(User user); //删除用户 int deleteUser(int id); }
-
在
UserMapperImpl
重写方法package com.jiang.mapper.impl; import com.jiang.pojo.User; import com.jiang.mapper.UserMapper; import org.mybatis.spring.SqlSessionTemplate; import java.util.List; //实现类 public class UserMapperImpl implements UserMapper { //注入sqlSession: Spring管理了 private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } //查询用户 @Override public List<User> getUserList() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.getUserList(); } //添加用户 @Override public int addUser(User user) { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.addUser(user); } //删除用户 @Override public int deleteUser(int id) { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.deleteUser(id); } }
-
在
UserMapper.xml
里编写sql<?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"> <!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.jiang.mapper.UserMapper"> <!--select查询语句--> <select id="getUserList" resultType="com.jiang.pojo.User"> select * from mybatis.user </select> <!--insert添加语句--> <insert id="addUser" parameterType="User"> insert into user (id,name,pwd) values (#{id},#{name},#{pwd}) </insert> <!--delete删除语句--> <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete> </mapper>
-
在
applicationContext.xml
头文件中添加事务和AOP支持,并整合事务!<!--添加事务和AOP支持 我这边是在上面那些支持存在的情况下加这些 这里只是为了更简洁突出事务和AOP支持--> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--整合事务--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <constructor-arg ref="dataSource" /> </bean> <!--事务配置增强,一定要检查pom.xml文件中有没有aop aspectjweaver 织入包--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!--propagation 事务的传播特性 默认REQUIRED--> <!-- * 控制所有方法--> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <!--切入点--> <aop:pointcut id="txPointCut" expression="execution(* com.jiang.mapper.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> </beans>
-
测试
@Test public void test3(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapperImpl = (UserMapper) context.getBean("userMapperImpl"); userMapperImpl.addUser(new User(4,"嘻嘻","898798")); }
测试成功!
注意事项:
如果把测试类中的:
UserMapper userMapperImpl = (UserMapper) context.getBean("userMapperImpl");
改为:
UserMapperImpl userMapperImpl = (UserMapperImpl) context.getBean("userMapperImpl");
会报类型转换异常:
java.lang.ClassCastException: com.sun.proxy.$Proxy8 cannot be cast to com.jiang.mapper.impl.UserMapperImpl
原因解释参考博客:https://blog.csdn.net/yinzn2011/article/details/46455973