MyBatis, Spring Integration (Eclipse), and transaction management

Source: Internet
Author: User
Tags connection pooling log4j

1. Project Catalogue

2. Jar Package

    • DBCP: Connection pooling
    • Pool: Connection Pooling
    • Logging: Log
    • log4j: Log
    • Mybatis-spring: For sqlsession and other related operations
    • Spring Related Packages
    • MyBatis
3. Web. XML configuration
    • This configuration file can be deleted, this test is junit, does not involve network access, all this configuration file does not need
<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "> <display-name>transactiondome </display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> < Welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> < Welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> < welcome-file>default.jsp</welcome-file> </welcome-file-list> <listener> <listener-class >org.springframework.web.context.ContextLoaderListener</listener-class> </listener> < Context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spri Ng-mybatis.xml</param-value> </context-param> <servlet> <servlet-name>springservlet</serv Let-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> < Init-param> <param-name>contextConfigLocation</param-name> <param-value></para m-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <serv Let-mapping> <servlet-name>springServlet</servlet-name> <url-pattern>/</url-pattern&gt   ; </servlet-mapping></web-app>
4. Spring-mybatis.xml Configuration
    • The comments are detailed enough to stop detailing
<?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:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi: schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schem                           A/beans/spring-beans-3.1.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spring-context-3.1.xsd Http://www.springframe Work.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <!- -Auto Scan--<context:component-scan base-package= "Com.sysker.spring.dome"/> <!--Introduction profile--&lt ; Bean id= "Propertyconfigurer" class="Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name= "Location" value= " Classpath:jdbc.properties "/> </bean> <!--connection Pool configuration--<bean id=" DataSource "class=" Org.apache. Commons.dbcp.BasicDataSource "destroy-method=" Close "> <property name=" driverclassname "value=" ${driv ER} "/> <property name=" url "value=" ${url} "/> <property name=" username "value=" ${username} "/ > <property name= "password" value= "${password}"/> <!--Initialize connection size--<property NA Me= "InitialSize" value= "${initialsize}" ></property> <!--the maximum number of connection pools--<property name= "Max Active "value=" ${maxactive} "></property> <!--connection Pool Max idle--<property name=" Maxidle "value = "${maxidle}" ></property> <!--connection Pool min Idle--<property name= "Minidle" value= "${minidle}" &G      T;</property>   <!--get connection maximum wait time-<property name= "maxwait" value= "${maxwait}" ></property> </bean> <!--spring and MyBatis are perfectly integrated without the need for MyBatis configuration mapping files---<bean id= "sqlsessionfactory" class= "org.mybatis.spring.Sq Lsessionfactorybean "> <property name=" dataSource "ref=" DataSource "/> <!--automatically scan mapping.xml files- -<property name= "mapperlocations" value= "Classpath:com/sysker/spring/dome/mapping/*.xml" ></property > </bean> <!--DAO interface with the package name, Spring automatically finds the class under it--<bean class= "Org.mybatis.spring.mapper.MapperS Cannerconfigurer "> <property name=" basepackage "value=" Com.sysker.spring.dome.dao "/> <propert Y name= "sqlsessionfactorybeanname" value= "sqlsessionfactory" ></property> </bean> <!--(transaction management) TRA Nsaction Manager, use Jtatransactionmanager for global TX--<bean id= "TransactionManager" class= "Org.s Pringframework.jdbc.datasOurce. Datasourcetransactionmanager "> <property name=" dataSource "ref=" DataSource "/> </bean> & lt;! --Configure Transaction Management templates: Spring provides class-<bean id= "Transactiontemplate" class= to simplify transaction-managed code Org.springframework.transaction.support.TransactionTemplate "> <property name=" TransactionManager "ref="   TransactionManager "></property> </bean> </beans>
5. Jdbc.properties Configuration
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/spring?characterEncoding=UTF-8&amp;useSSL=false username=rootpassword=rootinitialSize=0  maxActive=20  maxIdle=20   minIdle=1  
6. log4j Configuration (log)
#定义LOG输出级别  log4j.rootLogger=INFO,Console,File  #定义日志输出目的地为控制台  log4j.appender.Console=org.apache.log4j.ConsoleAppender  log4j.appender.Console.Target=System.out  #可以灵活地指定日志输出格式,下面一行是指定具体的格式  log4j.appender.Console.layout = org.apache.log4j.PatternLayout  log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n   #文件大小到达指定尺寸的时候产生一个新的文件  log4j.appender.File = org.apache.log4j.RollingFileAppender  #指定输出目录  log4j.appender.File.File = logs/ssm.log  #定义文件最大大小  log4j.appender.File.MaxFileSize = 10MB  # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志  log4j.appender.File.Threshold = ALL  log4j.appender.File.layout = org.apache.log4j.PatternLayout  log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
7. Entity and Mapping.xml
package com.sysker.spring.dome.entity;public class Account {    // 账户id    private String id;    // 账号名    private String name;    // 余额    private String money;    public Account() {        super();    }    public Account(String id, String name, String money) {        super();        this.id = id;        this.name = name;        this.money = money;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getMoney() {        return money;    }    public void setMoney(String money) {        this.money = money;    }}
    • Because direct mapping is used directly in the parameters, so the entity class is not used
<?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.sysker.spring.dome.dao.AccountDao">    <update id="inMoney">        update account set        money = money + #{arg1}        where name = #{arg0}    </update>        <update id="outMoney">        update account set        money = money - #{arg1}        where name = #{arg0}    </update></mapper>
8. Dao
package com.sysker.spring.dome.dao;public interface AccountDao {    void outMoney(String out, String money);    void inMoney(String in, String money);}
9. Service and Serviceimpl
package com.sysker.spring.dome.service;public interface AccountService {        void transfer(String out, String in, String money);}

Service implementation that includes transaction management

Package Com.sysker.spring.dome.service.impl;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Org.springframework.transaction.transactionstatus;import Org.springframework.transaction.support.transactioncallbackwithoutresult;import Org.springframework.transaction.support.transactiontemplate;import Com.sysker.spring.dome.dao.accountdao;import Com.sysker.spring.dome.service.AccountService, @Servicepublic class Accountserviceimpl implements Accountservice {@        autowired private Accountdao Accountdao;        @Autowired private Transactiontemplate transactiontemplate; An anonymous inner class is created @Override public void transfer (string-out, string-in, string-Money) {/** * transaction management, execute () method.                        Transaction management can be achieved by operating the business in an anonymous internal class */Transactiontemplate.execute (new Transactioncallbackwithoutresult () { @Override protected void Dointransactionwithoutresult (Transactionstatus transactionstATUs) {Accountdao.outmoney (out, money);                int i = 1/0;                            Accountdao.inmoney (in, money);                    }        }); }}
10. Test class
package com.sysker.spring.dome.test;import javax.annotation.Resource;import org.apache.log4j.Logger;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.sysker.spring.dome.service.AccountService;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})public class TestMybatis {    private static Logger logger = Logger.getLogger(TestMybatis.class);    @Resource    private AccountService accountService = null;        @Test    public void test1() {        accountService.transfer("aaa", "bbb", "200");        logger.info("success");            }    }
Summarize
    • Today in MU class network learning, originally intended to achieve transaction management, but found that the teacher in the video is a JDBC connection, so the teacher's ideas, to achieve the mybatis-spring integration, the process is difficult, but it is full of harvest:
      • 1, the dependency injection has a deeper understanding and cognition, Spring has a more comprehensive cognition, of course, more still find themselves too shallow to understand;
      • 2, more practice, more trying, more thinking, more pondering, more summary, when you step through all the pits, you are not far from becoming God's Road
      • 3, I always prefer to learn in the bug, every fill out a pit is exciting, but also harvest a lot of

MyBatis, Spring Integration (Eclipse), and transaction management

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.