springMVC4.x+spring4+Mybatis3整合

文章目录

  • 1.各框架在整合过程中的作用
  • 整合步骤
    • 第一步:导入jar包(springmvc4.x、spring4.x、mybatis3、整合的jar)
    • 创建文件结构
    • 导入jar包
    • 第二步:书写配置文件springmvc.xml、applicationContext.xml、web.xml、mybatis
      • springmvc.xml
      • applicationContext.xml
      • web.xml
      • mybatis
    • 第三步:启动框架测试
      • jsp
      • controller层
      • service层
      • mapper层
        • entity
    • 事务
      • controller层
      • service层
      • entity
      • mapper
        • 1553424350566|4|statement|connection 1|UPDATE account SET money=money+? WHERE bankNo=?|UPDATE account SET money=money+-200 WHERE bankNo='110'
        • 1553424350575|8|rollback|connection 1||

1.各框架在整合过程中的作用

springMVC4.x+spring4+Mybatis3整合_第1张图片

整合步骤

第一步:导入jar包(springmvc4.x、spring4.x、mybatis3、整合的jar)

创建文件结构

springMVC4.x+spring4+Mybatis3整合_第2张图片

导入jar包

springMVC4.x+spring4+Mybatis3整合_第3张图片
springMVC4.x+spring4+Mybatis3整合_第4张图片

第二步:书写配置文件springmvc.xml、applicationContext.xml、web.xml、mybatis

springmvc.xml


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
			http://www.springframework.org/schema/mvc 
			http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
			http://www.springframework.org/schema/context 
			http://www.springframework.org/schema/context/spring-context-4.2.xsd 
			http://www.springframework.org/schema/task   
	   		http://www.springframework.org/schema/task/spring-task-4.2.xsd">
	   		
	   		
	
	<context:component-scan base-package="cn.java.controller.*"/>
	
	
	<mvc:annotation-driven/>
	
	
	<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		
		<property name="prefix" value="/pages/">property>
		
		<property name="suffix" value="">property>
	bean>
	
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		
		<property name="defaultEncoding" value="utf-8">property>
		
		<property name="maxUploadSize" value="1048576">property>
	bean>
	
	
beans>

applicationContext.xml


<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:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
       
       	
       <context:component-scan base-package="cn.java.service.impl"/>
       
       
       <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       		
       		<property name="location" value="classpath:database.properties">property>
       bean>
       
       
       <bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
       		
       		<property name="driverClassName" value="${driver}"/>
			<property name="url" value="${url}"/>
			<property name="username" value="${username}"/>
			<property name="password" value="${password}"/>
       bean>
       
       
       <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
       		
       		<property name="dataSource" ref="basicDataSource">property>
       		
       		<property name="mapperLocations" value="classpath*:cn/java/mapper/*.xml">property>
       bean>
       
       
       <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       		
       		<property name="basePackage" value="cn.java.mapper">property>
       bean>
       
       
       
       

beans>

web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ssmdisplay-name>
  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>
  
  
  <filter>
  	<filter-name>characterEncodingFilterfilter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
  	<init-param>
  		<param-name>encodingparam-name>
  		<param-value>utf-8param-value>
  	init-param>
  filter>
  <filter-mapping>
  	<filter-name>characterEncodingFilterfilter-name>
  	<url-pattern>/*url-pattern>
  filter-mapping>
  
  
  <context-param>
  	<param-name>contextConfigLocationparam-name>
  	<param-value>classpath:applicationContext.xmlparam-value>
  context-param>
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  
  
  <servlet>
  	<servlet-name>dispatcherServletservlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
  	<init-param>
  		<param-name>contextConfigLocationparam-name>
  		<param-value>classpath:springmvc.xmlparam-value>
  	init-param>
  	<load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
  	<servlet-name>dispatcherServletservlet-name>
  	<url-pattern>*.shtmlurl-pattern>
  servlet-mapping>
  
  
  <error-page>
  	<error-code>404error-code>
  	<location>/pages/error/404.jsplocation>
  error-page>
  
web-app>

mybatis

目前没用到,用到再配

第三步:启动框架测试

新建index.jsp能启动不报错基本就算搭建成功了

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页title>
<script type="text/javascript" src="jquery-3.3.1.js">script>
<script type="text/javascript">

script>
head>
<body>
	<h1>HELLO WORLDh1>
	<form action="<%=basePath%>/getPersonById.shtml">
		<input type="text" name="id" >
		<input type="submit" value="提交">
	form>
body>
html>

接下来写一个查询测试框架。

springMVC4.x+spring4+Mybatis3整合_第5张图片

controller层

package cn.java.controller.front;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.java.entity.Person;
import cn.java.entity.QQ;
import cn.java.service.PersonService;

/**
 * @Description: TODO
 * @Title:  FrontController.java
 * @author: Matthew
 * @date: 2019年3月20日 下午8:19:22
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/front/")
public class FrontController {
	@Autowired
	private PersonService ps;
	
	@RequestMapping("getPersonById")
	@ResponseBody
	public Person getPersonById(Long id){
		return ps.selectByPrimaryKey(id);
	}
}

service层

package cn.java.service;

import cn.java.entity.Person;

public interface PersonService {
    int deleteByPrimaryKey(Long id);

    int insert(Person record);

    int insertSelective(Person record);

    Person selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(Person record);

    int updateByPrimaryKey(Person record);
    
    int zhuanMoney(String bankNo1, String bankNo2, Integer money);

}
package cn.java.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.java.entity.Person;
import cn.java.mapper.AccountMapper;
import cn.java.mapper.PersonMapper;
import cn.java.service.PersonService;


/**
 * @Description: TODO
 * @Title:  PersonServiceImpl.java
 * @author: Matthew
 * @date: 2019年3月20日 下午8:14:06
 * @version V1.0
 */
@Service
public class PersonServiceImpl implements PersonService {
	@Autowired
	private PersonMapper pm;
	@Autowired
	private AccountMapper am;

	@Override
	public int deleteByPrimaryKey(Long id) {
		return 0;
	}


	@Override
	public int insert(Person record) {
		return 0;
	}


	@Override
	public int insertSelective(Person record) {
		return 0;
	}

	/**
	 * 根据指定id查询用户
	 */
	@Override
	public Person selectByPrimaryKey(Long id) {
		
		return pm.selectByPrimaryKey(id);
	}


	@Override
	public int updateByPrimaryKeySelective(Person record) {
		return 0;
	}


	@Override
	public int updateByPrimaryKey(Person record) {
		return 0;
	}

	@Transactional(readOnly = false, rollbackFor = Exception.class)//使方法具有事务性
	@Override
	public int zhuanMoney(String bankNo1, String bankNo2, Integer money){
		//1.给宝强-200万
		System.out.println("hahahah");
		int result1 = am.updateMoney(-money, bankNo1);
//		result1 = 1/0;
		if (result1 >= 1) {
			//2.给马荣+200万
			result1 = am.updateMoney(money, bankNo2);
		}
		
		return result1;
	}

}

mapper层

entity

package cn.java.entity;

public class Person {
    private Long id;

    private String username;

    private String idcard;

    private String gender;

    private String address;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getIdcard() {
        return idcard;
    }

    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
package cn.java.mapper;

import cn.java.entity.Person;

public interface PersonMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Person record);

    int insertSelective(Person record);

    Person selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(Person record);

    int updateByPrimaryKey(Person record);
    
}


<mapper namespace="cn.java.mapper.PersonMapper">
	<resultMap id="BaseResultMap" type="cn.java.entity.Person">
		<id column="id" property="id" jdbcType="BIGINT" />
		<result column="username" property="username" jdbcType="VARCHAR" />
		<result column="idcard" property="idcard" jdbcType="VARCHAR" />
		<result column="gender" property="gender" jdbcType="VARCHAR" />
		<result column="address" property="address" jdbcType="VARCHAR" />
	resultMap>
	<sql id="Base_Column_List">
		id, username, idcard, gender, address
	sql>
	<select id="selectByPrimaryKey" resultMap="BaseResultMap"
		parameterType="java.lang.Long">
		select
		<include refid="Base_Column_List" />
		from persons
		where id = #{id,jdbcType=BIGINT}
	select>
	<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
		delete from persons
		where id = #{id,jdbcType=BIGINT}
	delete>
	<insert id="insert" parameterType="cn.java.entity.Person">
		insert into persons (id, username, idcard,
		gender, address)
		values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR},
		#{idcard,jdbcType=VARCHAR},
		#{gender,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR})
	insert>
	<insert id="insertSelective" parameterType="cn.java.entity.Person">
		insert into persons
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="id != null">
				id,
			if>
			<if test="username != null">
				username,
			if>
			<if test="idcard != null">
				idcard,
			if>
			<if test="gender != null">
				gender,
			if>
			<if test="address != null">
				address,
			if>
		trim>
		<trim prefix="values (" suffix=")" suffixOverrides=",">
			<if test="id != null">
				#{id,jdbcType=BIGINT},
			if>
			<if test="username != null">
				#{username,jdbcType=VARCHAR},
			if>
			<if test="idcard != null">
				#{idcard,jdbcType=VARCHAR},
			if>
			<if test="gender != null">
				#{gender,jdbcType=VARCHAR},
			if>
			<if test="address != null">
				#{address,jdbcType=VARCHAR},
			if>
		trim>
	insert>
	<update id="updateByPrimaryKeySelective" parameterType="cn.java.entity.Person">
		update persons
		<set>
			<if test="username != null">
				username = #{username,jdbcType=VARCHAR},
			if>
			<if test="idcard != null">
				idcard = #{idcard,jdbcType=VARCHAR},
			if>
			<if test="gender != null">
				gender = #{gender,jdbcType=VARCHAR},
			if>
			<if test="address != null">
				address = #{address,jdbcType=VARCHAR},
			if>
		set>
		where id = #{id,jdbcType=BIGINT}
	update>
	<update id="updateByPrimaryKey" parameterType="cn.java.entity.Person">
		update persons
		set username = #{username,jdbcType=VARCHAR},
		idcard = #{idcard,jdbcType=VARCHAR},
		gender = #{gender,jdbcType=VARCHAR},
		address = #{address,jdbcType=VARCHAR}
		where id = #{id,jdbcType=BIGINT}
	update>
mapper>

springMVC4.x+spring4+Mybatis3整合_第6张图片

事务

王宝强给马荣转200w,如果正在王宝强扣完钱后系统出错,王宝强的钱应该回滚
springMVC4.x+spring4+Mybatis3整合_第7张图片

controller层

@RequestMapping("zhuanMoney")
	@ResponseBody
	public Integer zhuanMoney(String bankNo1, String bankNo2, Integer money){
		return ps.zhuanMoney(bankNo1, bankNo2, money);
	}

service层

@Transactional(readOnly = false, rollbackFor = Exception.class)//使方法具有事务性
	@Override
	public int zhuanMoney(String bankNo1, String bankNo2, Integer money){
		//1.给宝强-200万
		System.out.println("hahahah");
		int result1 = am.updateMoney(-money, bankNo1);
		result1 = 1/0;
		if (result1 >= 1) {
			//2.给马荣+200万
			result1 = am.updateMoney(money, bankNo2);
		}
		
		return result1;
	}

entity

package cn.java.entity;

public class Account {
    private Long id;

    private String bankno;

    private String username;

    private Integer money;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getBankno() {
        return bankno;
    }

    public void setBankno(String bankno) {
        this.bankno = bankno;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getMoney() {
        return money;
    }

    public void setMoney(Integer money) {
        this.money = money;
    }
}

mapper

package cn.java.mapper;

import cn.java.entity.Account;

public interface AccountMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Account record);

    int insertSelective(Account record);

    Account selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(Account record);

    int updateByPrimaryKey(Account record);

    // 转账
    int updateMoney(Integer money, String bankNo);
}


<mapper namespace="cn.java.mapper.AccountMapper" >
  <resultMap id="BaseResultMap" type="cn.java.entity.Account" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="bankNo" property="bankno" jdbcType="VARCHAR" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="money" property="money" jdbcType="INTEGER" />
  resultMap>
  <sql id="Base_Column_List" >
    id, bankNo, username, money
  sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from account
    where id = #{id,jdbcType=BIGINT}
  select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from account
    where id = #{id,jdbcType=BIGINT}
  delete>
  <insert id="insert" parameterType="cn.java.entity.Account" >
    insert into account (id, bankNo, username, 
      money)
    values (#{id,jdbcType=BIGINT}, #{bankno,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, 
      #{money,jdbcType=INTEGER})
  insert>
  <insert id="insertSelective" parameterType="cn.java.entity.Account" >
    insert into account
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      if>
      <if test="bankno != null" >
        bankNo,
      if>
      <if test="username != null" >
        username,
      if>
      <if test="money != null" >
        money,
      if>
    trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=BIGINT},
      if>
      <if test="bankno != null" >
        #{bankno,jdbcType=VARCHAR},
      if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      if>
      <if test="money != null" >
        #{money,jdbcType=INTEGER},
      if>
    trim>
  insert>
  <update id="updateByPrimaryKeySelective" parameterType="cn.java.entity.Account" >
    update account
    <set >
      <if test="bankno != null" >
        bankNo = #{bankno,jdbcType=VARCHAR},
      if>
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      if>
      <if test="money != null" >
        money = #{money,jdbcType=INTEGER},
      if>
    set>
    where id = #{id,jdbcType=BIGINT}
  update>
  <update id="updateByPrimaryKey" parameterType="cn.java.entity.Account" >
    update account
    set bankNo = #{bankno,jdbcType=VARCHAR},
      username = #{username,jdbcType=VARCHAR},
      money = #{money,jdbcType=INTEGER}
    where id = #{id,jdbcType=BIGINT}
  update>
  
  
  <update id="updateMoney">
    UPDATE account SET money=money+#{0} WHERE bankNo=#{1}
  update>
mapper>

hahahah
2019-03-24 18:45:50,516 org.apache.ibatis.logging.slf4j.Slf4jLoggerImpl.debug(Slf4jLoggerImpl.java:54) Creating a new SqlSession
2019-03-24 18:45:50,521 org.apache.ibatis.logging.slf4j.Slf4jLoggerImpl.debug(Slf4jLoggerImpl.java:54) Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7cf214f7]
2019-03-24 18:45:50,529 org.apache.ibatis.logging.slf4j.Slf4jLoggerImpl.debug(Slf4jLoggerImpl.java:54) JDBC Connection [jdbc:mysql://localhost:3306/dt48?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT, UserName=root@localhost, MySQL Connector/J] will be managed by Spring
2019-03-24 18:45:50,530 org.apache.ibatis.logging.slf4j.Slf4jLoggerImpl.debug(Slf4jLoggerImpl.java:54) ==> Preparing: UPDATE account SET money=money+? WHERE bankNo=?
2019-03-24 18:45:50,561 org.apache.ibatis.logging.slf4j.Slf4jLoggerImpl.debug(Slf4jLoggerImpl.java:54) ==> Parameters: -200(Integer), 110(String)

1553424350566|4|statement|connection 1|UPDATE account SET money=money+? WHERE bankNo=?|UPDATE account SET money=money±200 WHERE bankNo=‘110’

2019-03-24 18:45:50,566 org.apache.ibatis.logging.slf4j.Slf4jLoggerImpl.debug(Slf4jLoggerImpl.java:54) <== Updates: 1
2019-03-24 18:45:50,566 org.apache.ibatis.logging.slf4j.Slf4jLoggerImpl.debug(Slf4jLoggerImpl.java:54) Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7cf214f7]
2019-03-24 18:45:50,566 org.apache.ibatis.logging.slf4j.Slf4jLoggerImpl.debug(Slf4jLoggerImpl.java:54) Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7cf214f7]
2019-03-24 18:45:50,567 org.apache.ibatis.logging.slf4j.Slf4jLoggerImpl.debug(Slf4jLoggerImpl.java:54) Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7cf214f7]
2019-03-24 18:45:50,567 org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:851) Initiating transaction rollback
2019-03-24 18:45:50,567 org.springframework.jdbc.datasource.DataSourceTransactionManager.doRollback(DataSourceTransactionManager.java:284) Rolling back JDBC transaction on Connection [jdbc:mysql://localhost:3306/dt48?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT, UserName=root@localhost, MySQL Connector/J]

1553424350575|8|rollback|connection 1||

java.lang.ArithmeticException: / by zero

我们这里用到的注解就是
@Transactional(readOnly = false, rollbackFor = Exception.class)
readOnly默认就是false可以省略,rollbackFor 后面跟的是遇到什么异常回滚
要使用这个注解需要在applicationContext.xml里配置


       <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       		<property name="dataSource" ref="basicDataSource">property>
       bean>
       
       <tx:annotation-driven transaction-manager="dataSourceTransactionManager" proxy-target-class="true"/>

你可能感兴趣的:(Spring,MVC)