您好,登錄后才能下訂單哦!
Spring SpringMVC,Spring整合MyBatis 事務配置的方法?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
(1)SSM是什么?
Spring,SpringMVC,Mybastis
(2)思路
搭建整合的環境,初始化環境
搭建Spring環境,配置完成并測試 (service層)
再使用Spring整合MyBatis框架,并測試(Dao層)
最后使用Spring整合SpringMVC框架,并測試(web層)
(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
思路
(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
<?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" 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>
配置Mybatis(原來沒用spring的)
)
(1)SqlMapConfig.xml
》》指定四大信息:賬號密碼ip端口
》》指定domain別名
》》指定映射文件
(2)編寫測試
》》保存
》》查詢
SqlMapConfig.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> <!-- 別名 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
<?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.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)); } }
(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); }
(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頁面進行展示數據
<?xml version="1.0" encoding="UTF-8"?> <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 事務配置的方法問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。