教你一步步搭建ssm框架,第二步集成mybatis实现数据的保存
原创 java_world 发表于:2018-05-08 19:56:51
  阅读 :59   收藏   编辑

上一步:教你一步步搭建ssm框架,第一步实现springmvc下的页面跳转

这一步我们将集成mybatis,实现数据的保存,数据库这里我们使用mysql

先看一下整体的结构

pom.xml 新增,上一步依赖漏掉了

<!-- mybatis s -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
<!-- mybatis e -->

第一步:编辑classpath下的res.properties 新增mysql数据库连接配置,新增如下

jdbc.c3p0.testConnectionOnCheckout=false
jdbc.c3p0.testConnectionOnCheckin=true
jdbc.c3p0.idleConnectionTestPeriod=3600
jdbc.c3p0.initialPoolSize=10
jdbc.c3p0.minPoolSize=10
jdbc.c3p0.maxPoolSize=100
jdbc.c3p0.maxIdleTime=3600
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/app_test?Unicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=root

第二步:mysql创建app数据库,测试表,编码均为utf-8

create database app_test;
create table test(
    id int auto_increment,
    user_name varchar(20),
    addr varchar(500),
    sex tinyint(4),
    primary key(id)

);

第三步:classpath下spring目录下新增mybatis_spring.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:cache="http//www.springframework.org/schema/cache"
    xsi:schemaLocation="
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">


     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close" 
        p:driverClass="${jdbc.driverClassName}"
        p:jdbcUrl="${jdbc.url}" 
        p:user="${jdbc.username}" 
        p:password="${jdbc.password}"
        p:testConnectionOnCheckout="${jdbc.c3p0.testConnectionOnCheckout}"
        p:testConnectionOnCheckin="${jdbc.c3p0.testConnectionOnCheckin}"
        p:idleConnectionTestPeriod="${jdbc.c3p0.idleConnectionTestPeriod}"
        p:initialPoolSize="${jdbc.c3p0.initialPoolSize}" 
        p:minPoolSize="${jdbc.c3p0.minPoolSize}"
        p:maxPoolSize="${jdbc.c3p0.maxPoolSize}" 
        p:maxIdleTime="${jdbc.c3p0.maxIdleTime}" />

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis_cfg.xml" />
        <property name="mapperLocations" value="classpath:com/faceghost/app/dao/mapper/**/*.xml"/>
        <property name="typeAliasesPackage" value="com.faceghost.app.model"/>
    </bean>

    <!-- mybatis SqlTemplate -->
    <bean id="sqlTemplate" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
         <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>


    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.faceghost.app.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  
</beans>

第四步:classpath下spring目录下新增transaction_spring.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:cache="http//www.springframework.org/schema/cache"
    xsi:schemaLocation="
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">


    <!-- 事物管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!-- spring 注解事物配置 -->
    <tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager"/>


    <!-- spring 声明式事物配置 start -->
    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="update*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="delete*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="exec*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="create*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="auto*" isolation="DEFAULT" read-only="false" propagation="REQUIRES_NEW" rollback-for="Exception"/>
            <tx:method name="get*" isolation="DEFAULT" read-only="true" propagation="NOT_SUPPORTED" />
            <tx:method name="*" isolation="DEFAULT"   read-only="true"  propagation="NOT_SUPPORTED" />  
        </tx:attributes>
    </tx:advice>

    <aop:config proxy-target-class="true">
        <aop:pointcut expression="execution(* com.faceghost.app.service..*.*(..))" id="pointCut"/>
        <aop:advisor advice-ref="advice" pointcut-ref="pointCut"/>
    </aop:config>
    <!-- spring 声明式事物配置 end -->

</beans>

第五步:编辑spring_context.xml,导入我们刚刚新增的2个文件,整体如下

<?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:cache="http://www.springframework.org/schema/cache" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">




    <!-- spring xml事物管理 -->
    <import resource="spring/transaction_spring.xml" />

    <!-- spring mybatis -->
    <import resource="spring/mybatis_spring.xml" />


     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
          <property name="locations">
              <list>
                <value>classpath:res.properties</value>
            </list>
          </property>
    </bean>

    <context:annotation-config />

     <!-- 配置扫描路径 -->
     <context:component-scan base-package="com.faceghost.app">
         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
     </context:component-scan>



</beans>

第六步:创建model,mapper,mapper.xml,service,controller内容如下

  • Test.java
package com.faceghost.app.model;

public class Test {
    private Integer id;

    private String userName;

    private String addr;

    private Byte sex;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr == null ? null : addr.trim();
    }

    public Byte getSex() {
        return sex;
    }

    public void setSex(Byte sex) {
        this.sex = sex;
    }
}
  • TestMapper.java
package com.faceghost.app.dao;

import org.springframework.stereotype.Repository;

import com.faceghost.app.model.Test;

@Repository("testMapper")
public interface TestMapper {

    int deleteByPrimaryKey(Integer id);

    int insert(Test record);

    int insertSelective(Test record);

    Test selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Test record);

    int updateByPrimaryKey(Test record);
}
  • TestMapper.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.faceghost.app.dao.TestMapper">
  <resultMap id="BaseResultMap" type="com.faceghost.app.model.Test">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="addr" jdbcType="VARCHAR" property="addr" />
    <result column="sex" jdbcType="TINYINT" property="sex" />
  </resultMap>
  <sql id="Base_Column_List">
    id, user_name, addr, sex
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from test
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from test
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.faceghost.app.model.Test">
    insert into test (id, user_name, addr, 
      sex)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{addr,jdbcType=VARCHAR}, 
      #{sex,jdbcType=TINYINT})
  </insert>
  <insert id="insertSelective" parameterType="com.faceghost.app.model.Test">
    insert into test
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="userName != null">
        user_name,
      </if>
      <if test="addr != null">
        addr,
      </if>
      <if test="sex != null">
        sex,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null">
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="addr != null">
        #{addr,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=TINYINT},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.faceghost.app.model.Test">
    update test
    <set>
      <if test="userName != null">
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="addr != null">
        addr = #{addr,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=TINYINT},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.faceghost.app.model.Test">
    update test
    set user_name = #{userName,jdbcType=VARCHAR},
      addr = #{addr,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=TINYINT}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>
  • TestService.java
package com.faceghost.app.service;

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

import com.faceghost.app.dao.TestMapper;
import com.faceghost.app.model.Test;

@Service
public class TestService {

    @Autowired()
    private TestMapper testMapper;

    public Test saveBean(Test bean) {
         testMapper.insert(bean);
         return bean;
    }
}
  • TestController.java
package com.faceghost.app.controller;

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

import com.faceghost.app.model.Test;
import com.faceghost.app.service.TestService;

@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("/saveTest")
    @ResponseBody
    public String saveTest(String userName,String addr,Byte sex) {
        Test bean = new Test();
        bean.setUserName(userName);
        bean.setAddr(addr);
        bean.setSex(sex);
        testService.saveBean(bean);
        return "success";
    }
}

第七步:浏览器访问,添加数据,这里映射地址:/test/saveTest?userName=张三&addr=SH&sex=1

http://localhost:8080/app/test/saveTest?userName=张三​&addr=SH​&sex=1

eclipse控制台打印

[2018-05-08 19:54:57.718]-[com.faceghost.app.dao.TestMapper.insert]-[http-bio-8080-exec-3]  - ==>  Preparing: insert into test (id, user_name, addr, sex) values (?, ?, ?, ?) 
[2018-05-08 19:54:57.752]-[com.faceghost.app.dao.TestMapper.insert]-[http-bio-8080-exec-3]  - ==> Parameters: null, 张三(String), SH(String), 1(Byte)
[2018-05-08 19:54:57.814]-[com.faceghost.app.dao.TestMapper.insert]-[http-bio-8080-exec-3]  - <==    Updates: 1

查看数据库