温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring SpringMVC,Spring整合MyBatis 事务配置的方法

发布时间:2020-10-26 15:07:17 来源:亿速云 阅读:268 作者:Leah 栏目:开发技术

Spring SpringMVC,Spring整合MyBatis 事务配置的方法?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

整合思路

(1)SSM是什么?
Spring,SpringMVC,Mybastis
(2)思路

搭建整合的环境,初始化环境
搭建Spring环境,配置完成并测试 (service层)
再使用Spring整合MyBatis框架,并测试(Dao层)
最后使用Spring整合SpringMVC框架,并测试(web层)

SSM搭建环境

(1)数据库创建ssm
(2)创建maven工程
(3)git (创建.gitignore来过滤不用提交的文件)
(4)依赖框架
(5)log4j.properties

数据库准备

create database ssm;
use ssm;
create table person(
 id int primary key auto_increment,
 `name` varchar(20),
 password varchar(20),
 money double
);

pom.xml

 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <maven.compiler.source>1.8</maven.compiler.source>
 <maven.compiler.target>1.8</maven.compiler.target>
 <spring.version>5.2.9.RELEASE</spring.version>
 <slf4j.version>1.6.6</slf4j.version>
 <log4j.version>1.2.12</log4j.version>
 <mysql.version>5.1.6</mysql.version>
 <mybatis.version>3.4.5</mybatis.version>
 </properties>

 <dependencies>
 <!-- spring -->
 <dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.6.8</version>
 </dependency>

 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>${spring.version}</version>
 </dependency>

 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring.version}</version>
 </dependency>

 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>${spring.version}</version>
 </dependency>

 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>${spring.version}</version>
 </dependency>

 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>${spring.version}</version>
 </dependency>

 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>${spring.version}</version>
 </dependency>

 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>${spring.version}</version>
 </dependency>

 <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
 </dependency>

 <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>${mysql.version}</version>
 </dependency>

 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.5</version>
  <scope>provided</scope>
 </dependency>

 <dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.0</version>
  <scope>provided</scope>
 </dependency>

 <dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
 </dependency>

 <!-- log start -->
 <dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>${log4j.version}</version>
 </dependency>

 <dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>${slf4j.version}</version>
 </dependency>

 <dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>${slf4j.version}</version>
 </dependency>

 <!-- mybatis -->
 <dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>${mybatis.version}</version>
 </dependency>

 <!-- spring Mybatis-->
 <dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.0</version>
 </dependency>

 <dependency>
  <groupId>c3p0</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.1.2</version>
  <type>jar</type>
  <scope>compile</scope>
 </dependency>

 </dependencies>

log4j.properties

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE  debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
# 输出到控制台
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
# 输出到日志文件
log4j.appender.LOGFILE.File=E:\logFile\SSM\ssm.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

搭建Spring环境,配置完成并测试 (service层)

思路

(1)编写业务类调用测试逻辑
》TestPersonService
》IPersonService PersonServiceImpl
》Person
(2)applicationContext.xml
(3)配置组件扫描 – 验证IOC
(4)配置哪些不扫描
(5)验证DI
》IPersonDao PersonDaoImpl

TestPersonService

package com.zx.service;

import com.zx.domain.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestPersonService {

 @Autowired
 IPersonService personService;

 @Test
 public void test(){
 Person person=new Person(1,"rose","123456",1000.00);

 List<Person> list= personService.findAll();
 System.out.println(list);
 personService.save(person);

 }
 
}

IPersonService

package com.zx.service;

import com.zx.domain.Person;

import java.util.List;

public interface IPersonService {
 List<Person> findAll();
 void save(Person person);
 void saves(List<Person> personList);
}

PersonServiceImpl

package com.zx.service;

import com.zx.dao.IPersonDao;
import com.zx.dao.PersonDaoImpl;
import com.zx.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class PersonServiceImpl implements IPersonService {
 @Qualifier("IPersonDao")
 @Autowired
 private IPersonDao personDao;
 @Override
 public List<Person> findAll() {
 List<Person> list=personDao.findAll();
 System.out.println(list);
 return list;
 }

 @Override
 public void save(Person person) {

 personDao.save(person);


 }

 @Override
 public void saves(List<Person> personList) {
 for(int i=0;i<personList.size();i++){
  personDao.save(personList.get(i));
 }
 }
}

Person

package com.zx.domain;

public class Person {
 private int id;
 private String name;
 private String password;
 private double money;

 省略....

applicationContext.xml

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<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"
 xmlns:aop="http://www.springframework.org/schema/aop"
 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/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

 <!-- 设置扫描包,包下设置注解@Service @Repository @Component @AutoWried-->
 <context:component-scan base-package="com.zx">
 <!-- 由于springmvc的controller是由springmvc来扫描,需要将controller排除在外-->
 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
 </context:component-scan>

 <!--将SqlMapConfig.xml的数据配置到spring中 四大信息-->
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"></property>
 <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
 <property name="user" value="root"></property>
 <property name="password" value="123456"></property>
 </bean>
 <!-- session工厂-->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="dataSource"/>
 <!-- com.zx.domain.Person person-->
 <property name="typeAliasesPackage" value="com.zx.domain"/>
 </bean>

 <!-- IPersonDao.xml的映射 IPersonDao.java-->
 <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 <property name="basePackage" value="com.zx.dao"/>
 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
 </bean>

 <!--配置Spring框架声明式事务管理-->
 <!--配置事务管理器-->
 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <property name="dataSource" ref="dataSource" />
 </bean>

 <tx:advice id="txAdvice" transaction-manager="transactionManager">
 <tx:attributes>
  <tx:method name="find*" read-only="true"/>
  <tx:method name="*" isolation="DEFAULT"/>
 </tx:attributes>
 </tx:advice>

 <!--配置AOP增强-->
 <aop:config>
 <aop:pointcut id="service" expression="execution(* com.zx.service.*ServiceImpl.*(..))"/>
 <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
 </aop:config>
</beans>

Spring整合Mybatis

配置Mybatis(原来没用spring的)

)
(1)SqlMapConfig.xml
》》指定四大信息:账号密码ip端口
》》指定domain别名
》》指定映射文件
(2)编写测试
》》保存
》》查询

SqlMapConfig.xml

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 <!-- 别名 com.wzx.domain.Person person-->
 <typeAliases>
 <package name="com.zx.domain"/>
 </typeAliases>
 <environments default="mysql">
 <environment id="mysql">
  <transactionManager type="JDBC"/>
  <dataSource type="POOLED">
  <property name="driver" value="com.mysql.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
  <property name="username" value="root"/>
  <property name="password" value="123456"/>
  </dataSource>
 </environment>
 </environments>
 <!-- 核心 配置文件扫描到映射文件-->
 <mappers>
 <package name="com.zx.dao"/>
 </mappers>
</configuration>

TestMyBatis

public class TestMyBatis {
 private SqlSession session;
 @Before
 public void init(){
 // 加载配置文件
 InputStream in = TestMyBatis.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
 // 创建SqlSessionFactory对象
 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
 // 创建SqlSession对象
  session = factory.openSession();
 }
 @After
 public void destory(){
 session.commit();
 session.close();
 }
 @Test
 public void test01(){
 //最核心对象是session
 // System.out.println(session);
 //Mybastis的特点是sql与代码是分开的,需要映射文件
 IPersonDao dao = session.getMapper(IPersonDao.class);
 List<Person> list = dao.findAll();
 System.out.println(list);
 }
 @Test
 public void test02(){
 //最核心对象是session

 IPersonDao dao = session.getMapper(IPersonDao.class);
 dao.save(new Person("tony",200.00));

 }
}

IPersonDao.xml

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zx.dao.IPersonDao">
 <select id="findAll" resultType="person">
  select * from person;
 </select>

 <insert id="save" parameterType="person">
 insert into person (name,money)values(#{name},#{money})
 </insert>
</mapper>

Spring整合Mybatis

(1)Spring整合MyBatis需要添加整合包
(2)什么是mybatis-spring
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中
不需要调用 session.getMapper(IpersonDao.class)
session.commit()
session.close()
(在测试Spring整合Mybatis时先不给DepartmentImpl加注解)

pom.xml

<dependency>
 <groupId>org.mybatis</groupId>
 <artifactId>mybatis-spring</artifactId>
 <version>1.3.0</version>
 </dependency>

applicationContext.xml

将SqlMapConfig.xml的数据配置到spring中

<!-- 四大信息-->
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"></property>
 <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
 <property name="user" value="root"></property>
 <property name="password" value="123456"></property>
 </bean>
 <!-- session工厂-->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="dataSource"/>
 <!-- com.wzx.domain.Person person-->
 <property name="typeAliasesPackage" value="com.wzx.domain"/>
 </bean>
 <!-- IPersonDao.xml IPersonDao.java-->
 <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.zx.dao"/>
  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

TestPersonDao

package com.zx.dao;

import com.zx.domain.Person;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestPersonDao {
 private SqlSession sqlSession;

 @Qualifier("IPersonDao")
 @Autowired
 IPersonDao personDao;

 @Test
 public void test01(){
 System.out.println(personDao);
 /* List<Person> list=personDao.findAll();

 System.out.println(list);*/
 personDao.save(new Person(3,"jackma","123456",12222222.00));

 }


}

Spring管理事务

(1)表达式设置有哪些serivce方法需要事务管理(2)通知设置 增删改业务方法 都要事务管理 具体对应的事务

applicationContext.xml

<!--配置Spring框架声明式事务管理-->
 <!--配置事务管理器-->
 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <property name="dataSource" ref="dataSource" />
 </bean>

 <tx:advice id="txAdvice" transaction-manager="transactionManager">
 <tx:attributes>
  <tx:method name="find*" read-only="true"/>
  <tx:method name="*" isolation="DEFAULT"/>
 </tx:attributes>
 </tx:advice>

 <!--配置AOP增强-->
 <aop:config>
 <aop:pointcut id="service" expression="execution(* com.wzx.service.impl.*ServiceImpl.*(..))"/>
 <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
 </aop:config>

TestPersonService

@Test
 public void test02(){
 List<Person> personList = new ArrayList<>();
 personList.add(new Person("jack",100.00));
 personList.add(new Person("rose",200.00));
 personList.add(new Person("tony",300.00));

 personService.saves(personList);
 }

使用Spring整合SpringMVC框架,并测试(web层)

(1)web.xml中配置前端控制器DispatcherServlet
SpringMVC的核心就是DispatcherServlet,DispatcherServlet实质也是一个HttpServlet。DispatcherSevlet负责将请求分发,所有的请求都有经过它来统一分发。
(2)web.xml中配置编码过滤器CharacterEncodingFilter
在 SpringMVC 中,框架直接给我们提供了一个用来解决请求和响应的乱码问题的过滤器 CharacterEncodingFilter
(3)web.xml中配置编码监听器ContextLoaderListener
web.xml中的配置文件中ContextLoaderListener作为监听器,会监听web容器相关事件,在web容器启动或者关闭时触发执行响应程序

web.xml 配置DispatcherServlet,CharacterEncodingFilter,ContextLoaderListener

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
 <display-name>Archetype Created Web Application</display-name>

 <!--设置配置文件的路径 service dao-->
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:applicationContext.xml</param-value>
 </context-param>


 <!--解决中文乱码的过滤器-->
 <filter>
 <filter-name>characterEncodingFilter</filter-name>
 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
 <init-param>
 <param-name>encoding</param-name>
 <param-value>UTF-8</param-value>
 </init-param>
 </filter>
 <filter-mapping>
 <filter-name>characterEncodingFilter</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>


 <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <!--配置前端控制器 controller-->
 <servlet>
 <servlet-name>dispatcherServlet</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <!--加载springmvc.xml配置文件-->
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:springmvc.xml</param-value>
 </init-param>
 <!--启动服务器,创建该servlet-->
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>dispatcherServlet</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

springmvc.xml

(1)springmvc中配置视图解析器,组件扫描,注解驱动
(2)配置springmvc对资源文件的放行
(3)编写一个PersonController测试
(4)编写一个list.jsp页面进行展示数据

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
 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/mvc
 http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context.xsd">
 <!--springmvc是web层 UserController @Controller -->
 <!-- 打开组件扫描-->
 <context:component-scan base-package="com.zx">
 <!-- 只处理带@Controller的请求-->
 <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
 </context:component-scan>

 <!--配置的视图解析器对象 /WEB-INF/pages/success.jsp -->
 <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/pages/"/>
 <property name="suffix" value=".jsp"/>
 </bean>
 <!--过滤静态资源 .js .css png-->
 <mvc:resources location="/css/" mapping="/css/**" />
 <mvc:resources location="/images/" mapping="/images/**" />
 <mvc:resources location="/js/" mapping="/js/**" />
 <!--开启SpringMVC注解的支持 @RequestMapping @RequestBody @ResponseBody-->
 <mvc:annotation-driven/>
</beans>

PersonController

@Controller
@RequestMapping("/person")
public class PersonController {
 @Autowired
 private IPersonService personService;

 @RequestMapping(path="/list",method = RequestMethod.GET)
 public String list(Model model){
 //显示所有的person数据
 List<Person> list = personService.findAll();
 System.out.println("list() list= "+list);
 //数据放在Model对象,由Model传给页面
 model.addAttribute("list",list);//参1 key 参2 value
 return "list";
 }
}

list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 <html>
<head>
 <title>Title</title>
</head>
<body>
<table border="1px" width="100%">
 <c:forEach items="${list}" var="person">
  <tr>
  <td>${person.id}</td>
  <td>${person.name}</td>
  <td>${person.money}</td>
  </tr>
 </c:forEach>
</table>
</body>
</html>

关于Spring SpringMVC,Spring整合MyBatis 事务配置的方法问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI