接上一章节继续SSM整合按步骤详解(清晰的思路加代码)从零开始一步步整合【一】
上面讲了Spring和SpringMVC的整合,现在开始下一步,先来搭建一下MyBatis的环境
我们先来看看目录结构图
首先需要配置文件,名字随意,我这里叫做MyBatisConfig.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>
<!--外部引入jdbc配置文件-->
<properties resource="jdbcConfig.properties"/>
<!-- 配置实体类别名,默认别名为类的字母(不区分大小写)-->
<typeAliases>
<package name="com.lp.domain"/>
</typeAliases>
<!--配置环境-->
<environments default="localhost">
<environment id="localhost">
<transactionManager type="JDBC"/>
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--配置dao接口所在位置-->
<mappers>
<package name="com.lp.dao"/>
</mappers>
</configuration>
上面所需要的jdbc配置文件写一下
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=962464
现在可以编写一下AccountDao的映射文件了,在这里面编写CRUD代码
<?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.lp.dao.AccountDao">
<!--如果实体类命名与数据库不一致就需要resultMap-->
<resultMap id="accountMap" type="Account">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="password" column="password"/>
</resultMap>
<select id="findAll" resultMap="accountMap">
select * from account;
</select>
<insert id="saveAccount" parameterType="Account">
insert into account
(name ,money)
values
(#{name},#{money});
</insert>
</mapper>
到这一步,MyBatis的环境搭建好了,开始测试一下是都搭建成功
package com.lp.test;
import com.lp.dao.AccountDao;
import com.lp.domain.Account;
import com.lp.service.AccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* @Date 2020/6/6 12:00
* @Author luopeng
*/
public class TestMyBatis {
@Test
public void testFindAll() throws IOException {
InputStream in = Resources.getResourceAsStream("MyBatisConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
for (Account account : accountDao.findAll()) {
System.out.println(account);
}
sqlSession.close();
in.close();
}
@Test
public void testSaveAccount() throws IOException {
InputStream in = Resources.getResourceAsStream("MyBatisConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
Account account = new Account();
account.setName("张三");
account.setMoney(5000D);
accountDao.saveAccount(account);
sqlSession.commit();
sqlSession.close();
in.close();
testFindAll();
}
}
只要上述操作都成功了,说明MyBatis环境搭建成功了!
注意,如果是从上一篇文章下载的同志,记得最后出错的原因是:我的c3p0连接池版本太低了,我去看了看,05年的,我最后Google,找到原因,换到了下面的版本
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.4</version>
</dependency>
现在开始,我们就要进行Spring和MyBatis的整合了,整合完成,整个项目就完成了
其实很简单,就是把原本需要MyBatis做的事情交给Spring来做,目的是为了把工厂生成的代理对象交给Spring来管理
首先,application.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启自动扫描 -->
<context:component-scan base-package="com.lp">
<!--配置哪些不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--Spring整合MyBatis框架-->
<!--jdbc配置文件引入Tomcat部署项目,
src/main/resources目录下的配置文件默认位置为:{项目名}/WEB-INF/classes,
而Spring却在项目根目录下寻找,肯定找不到,因此,配置时指定classpath目录下寻找。-->
<context:property-placeholder location="classpath:jdbcConfig.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>
<!--配置SqlSessionFactory工厂,
这一步是为了将MyBatis在工厂中生成的代理对象放在Spring容器中-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--给实体类取别名-->
<property name="typeAliasesPackage" value="com.lp.domain"/>
</bean>
<!--配置AccountDao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lp.dao"/>
</bean>
<!-- 配置Spring框架声明式事务管理-->
<!-- spring中基于XML的声明式事务控制配置步骤
1、配置事务管理器
2、配置事务的通知
此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop的
使用tx:advice标签配置事务通知
属性:
id:给事务通知起一个唯一标识
transaction-manager:给事务通知提供一个事务管理器引用
3、配置AOP中的通用切入点表达式
4、建立事务通知和切入点表达式的对应关系
5、配置事务的属性
是在事务的通知tx:advice标签的内部
-->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 配置事务的属性
isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。
timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="get*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="select*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!--配置AOP-->
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.lp.service.impl.*ServiceImpl.*(..))"/>
<!--配置事务通知与切入点表达式的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
</beans>
如果觉得太多了,可以把他分开配置,比如说,你要配置Spring和MyBatis的整合文件,你可以命名为spring-mybatis.xml,最后你最关键的一点记得在web.xml中让它能加载这个配置文件。当然事务管理的我们也可以单独来一个spring-service啦!
我踩过的坑在注释中有记录,也有提醒!