Java-Mybatis-Spring
概念
什么是 MyBatis-Spring?
- MyBatis-Spring会帮助你将MyBatis代码无缝地整合到Spring中。它将允许MyBatis参与到Spring的事务管理之中,创建映射器mapper和SqlSession并注入到bean中,以及将Mybatis的异常转换为Spring的DataAccessException。最终,可以做到应用代码不依赖于MyBatis,Spring或MyBatis-Spring。
核心原理
跟单独使用mybatis的区别
- 跟单独使用Mybatis类似,只是在此基础上让将Mybatis在Spring的配置中注册为bean,然后让Spring接管了Mybatis的一些配置项(甚至可以让Spring全部接管Mybatis配置,并删除原来的mybatis-config.xml核心配置文件)。
- 最终Mybatis在Spring中呈现为一个实现类为SqlSessionTemplate的bean(习惯上命名为:sqlSession),供程序在任意地方调用。
- Spring接管Mybatis以后多了一个实现类,在该类中定义一个sqlSession属性,并增加setter,然后在Spring注册bean并注入sqlSession属性即可。
- 新版本中还用另一种方式,让这个实现类继承SqlSessionDaoSupport,调用getSqlSession()方法你会得到一个SqlSessionTemplate。==注意:这种方式需要在bean中注入sqlSessionFactory属性,而不是sqlSession。==
其中两个核心bean
- sqlSessionFactory(SqlSessionFactoryBean)
- sqlSession(SqlSessionTemplate)
具体实现核心代码
目录机构
module
main
java
mapper
- UserMapper.java
- UserMapper.xml
- UserMapperImpl.java
- UserMapperImpl2.java
pojo
- User.java
resources
- applicationContext.xml
- jdbc.properties
- mybatis-config.xml
- spring-dao.xml
test
java
- UserMapperTest.java
- pom.xml
配置文件(resources)
pom.xml
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/jdbc_test?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai jdbc.username=root jdbc.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> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <typeAliases> <package name="cn.cnyasin.pojo"/> </typeAliases> <mappers> <mapper resource="cn/cnyasin/mapper/UserMapper.xml"/> </mappers> </configuration>
spring-dao.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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd "> <!-- 读取jdbc配置文件 --> <context:property-placeholder location="jdbc.properties"/> <!-- 定义DataSource:c3p0 dbcp druid --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 注册sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 绑定mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--<property name="mapperLocations" value="classpath:cn/cnyasin/mapper/UserMapper.xml"/>--> </bean> <!-- 注册sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!-- 注入SQLSessionFactory:只能通过构造器,因为他无set方法 --> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> </beans>
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 http://www.springframework.org/schema/beans/spring-beans.xsd "> <!-- 导入其他配置文件 --> <import resource="spring-dao.xml"/> <!-- mapper --> <!-- 方式一 --> <bean id="userMapper" class="cn.cnyasin.mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> <!-- 方式二 --> <bean id="userMapper2" class="cn.cnyasin.mapper.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans>
java代码
UserMapper.java
public interface UserMapper { public List<User> getAll(); }
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"> <mapper namespace="cn.cnyasin.mapper.UserMapper"> <resultMap id="userList" type="user"> <result property="createdAt" column="created_at"/> </resultMap> <select id="getAll" resultMap="userList"> select * from user </select> </mapper>
UserMapperImpl.java
public class UserMapperImpl implements UserMapper { private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } public List<User> getAll() { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); return userMapper.getAll(); } }
UserMapperImpl2.java
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{ public List<User> getAll() { return getSqlSession().getMapper(UserMapper.class).getAll(); } }
User.java
@NoArgsConstructor @AllArgsConstructor @Data public class User { private int id; private String username; private String email; private String password; private long balance; private long createdAt; }
UserMapperTest.java
public class UserMapperTest { @Test public void getAllTest() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); System.out.println(userMapper.getAll()); } @Test public void getAllTest2() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper2", UserMapper.class); System.out.println(userMapper.getAll()); } }
Mybatis配合Spring开启事务
如何理解?
不要被这个标题误导哦,Mybatis的事务非常笨重,而MybatisSpring中Mybatis默认关闭了事务,你可以直接使用Spring的事务。
- XML方式(配置事务通知、事务切入点)
- AOP方式(Spring开启注解、使用注解开启事务)
注意:最终实例化bean的时候,约束类必须是接口而不是接口的实现类,否则报错:
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userMapper' is expected to be of type......
- 错误用法:
UserMapperImpl userMapper = context.getBean("userMapper", UserMapperImpl.class);
- 正确用法:
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
- 错误用法: