MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。 最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring。
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.4version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.9.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.1.10.RELEASEversion>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.25version>
dependency>
public class School {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
package cn.supperbro.mapper;
import cn.supperbro.pojo.School;
import java.util.List;
public interface UserMapper {
List<School> findSchool();
}
当然还有sql的映射器
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.supperbro.mapper.UserMapper">
<select id="findSchool" resultType="school">
select * from school
select>
mapper>
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>
<typeAlias type="cn.supperbro.pojo.School" alias="school"/>
typeAliases>
configuration>
package cn.supperbro.mapper;
import cn.supperbro.pojo.School;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSession;
public UserMapperImpl(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<School> findSchool() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.findSchool();
}
}
<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">
<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/jdbctest?serverTimezone=UTC&useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value=""/>
<property name="password" value=""/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="mybatis-config.xml"/>
<property name="mapperLocations" value="cn/supperbro/mapper/UserMapper.xml"/>
bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
bean>
<bean class="cn.supperbro.mapper.UserMapperImpl" id="userMapper">
<constructor-arg index="0" ref="sqlSession"/>
bean>
beans>
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("mybatis-spring.xml");
UserMapper mapper = context.getBean("userMapper", UserMapper.class);
List<School> school = mapper.findSchool();
System.out.println(school);
//[School{name='武汉商学院', id=1}, School{name='武汉大学', id=2}, School{name='武汉理工大学', id=3}]
}
总结
mybatis单独使用时:
spring整合mybatis时:
<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/jdbctest?serverTimezone=UTC&useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value=""/>
<property name="password" value=""/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="mybatis-config.xml"/>
<property name="mapperLocations" value="cn/supperbro/mapper/UserMapper.xml"/>
bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
bean>
<bean class="cn.supperbro.mapper.UserMapperImpl" id="userMapper">
<constructor-arg index="0" ref="sqlSession"/>
bean>
注意:
上述过程中,加载数据源,我们的数据库配置文件是和spring的bean配置文件在一块的,我们可以通过引入context命名空间,加载db.properties文件。
<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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
通过 context:property-placeholder加载文件
<context:property-placeholder location="classpath:db.properties"/>
原来的数据源加载就可以写为
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
上诉代码中,数据源用的是spring-jdbc的,下面介绍spring配置其他的第三方数据源。配置数据源其实就是在第三方数据源注册到IOC中。
导入c3p0的依赖
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.2version>
dependency>
配置数据源
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
导入依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.3version>
dependency>
配置
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="2" />
<property name="minIdle" value="2" />
<property name="maxActive" value="30" />
<property name="testWhileIdle" value="false" />
<property name="maxWait" value="5000" />
<property name="minEvictableIdleTimeMillis" value="30000" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
bean>
重点注意xml的配置
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
bean>
<tx:advice id="transactionTest" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="test" expression="execution(* cn.supperbro.mapper.UserMapper.*(..))"/>
<aop:advisor advice-ref="transactionTest" pointcut-ref="test"/>
aop:config>
该配置详解:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
bean>
<tx:advice id="transactionTest" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
关于声明事务的配置由不同的Dao层操作来决定使用哪种配置。
tx:attributes该命名空间指定的是事务操作的属性
name为指定的事务生效的方法:例如
<tx:method name="add*" propagation="REQUIRED"/>
表示的所有以add开头的方法
-
<aop:config>
<aop:pointcut id="test" expression="execution(* cn.supperbro.mapper.UserMapper.*(..))"/>
<aop:advisor advice-ref="transactionTest" pointcut-ref="test"/>
aop:config>
<context:component-scan base-package="cn.supperbro.mapper"/>
@Repository("userMapper")
//该注解是注册该类
@Transactional
//该注解是将此类的所有方法添加事务操作
public class UserMapperImpl implements UserMapper {
@Autowired
//该注解自动匹配sqlSession对应的引用
private SqlSessionTemplate sqlSession;
@Override
@Transactional(propagation = Propagation.REQUIRED)
//也可以作用在方法上,表示对该方法起作用
public List<School> findSchool() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
School school = new School();
school.setId(11);
school.setName("北京大学");
add(school);
delete(11);
return mapper.findSchool();
}
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
bean>
下面为配置事务注解驱动,需要绑定上述的事务配置
<tx:annotation-driven transaction-manager="transactionManager"/>
好了,其他的就参考我们的官网