spring整合系列教程——spring整合mybatis

版权声明:转载请注明出处,谢谢 https://blog.csdn.net/m0_37867405/article/details/79293589

一、spring整合mybatis

1.首先您需要建立一个父pom工程,来管理jar包的版本

【项目结构图】 请自动忽略被遮挡的内容

这里写图片描述

【spring-root/pom.xml】

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.itcloud</groupId>
  <artifactId>spring-root</artifactId>
  <version>1.0-SNAPSHOT</version>
  <modules>
    <module>spring-mybatis</module>
    <module>spring-springmvc</module>
  </modules>
  <packaging>pom</packaging>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <springcontext.version>5.0.3.RELEASE</springcontext.version>
    <mybatis.version>3.4.5</mybatis.version>
    <mybatis-spring.version>1.3.1</mybatis-spring.version>
    <pagehelper.version>5.1.2</pagehelper.version>
    <druid.version>1.1.6</druid.version>
    <mysql.version>5.1.40</mysql.version>
    <junit.version>4.12</junit.version>
  </properties>
  <dependencyManagement>
    <dependencies>
      <!--spring的开发包-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <!--mybatis-->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
      </dependency>
      <!-- 分页插件 -->
      <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>${pagehelper.version}</version>
      </dependency>

      <!-- mybatis-spring -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>${mybatis-spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>${druid.version}</version>
      </dependency>
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
      </dependency>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>
</project>

2.建立spring-mybatis子模块

【mybatis文档】:http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Auto-mapping

项目结构:

这里写图片描述

在这一部分,我们只是做一个简单的整合,然后演示一个数据的增加操作,楼主会在下一节的内容中使用mybatis的逆向工程以及springboot进行详细的整合

【spring-mybatis/pom.xml文件】

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <parent>
        <artifactId>spring-root</artifactId>
        <groupId>com.itcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>spring-mybatis</artifactId>
    <packaging>war</packaging>
    <name>spring-mybatis Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <springcontext.version>5.0.3.RELEASE</springcontext.version>
    <mybatis.version>3.4.5</mybatis.version>
    <mybatis-spring.version>1.3.1</mybatis-spring.version>
    <pagehelper.version>5.1.2</pagehelper.version>
    <druid.version>1.1.6</druid.version>
    <mysql.version>5.1.40</mysql.version>
    <junit.version>4.12</junit.version>
  </properties>
    <dependencies>
      <!--spring的开发包-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <!--mybatis-->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
      </dependency>
      <!-- 分页插件 -->
      <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>${pagehelper.version}</version>
      </dependency>

      <!-- mybatis-spring -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>${mybatis-spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>${druid.version}</version>
      </dependency>
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
      </dependency>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
      </dependency>
    </dependencies>
    <build>
        <finalName>spring-mybatis</finalName>
    </build>
</project>

【数据库脚本.sql】

DROP DATABASE if EXISTS spring;
CREATE DATABASE spring;
USE spring;
DROP TABLE IF EXISTS goods;

CREATE TABLE goods(
  id        int AUTO_INCREMENT,
  title     VARCHAR(200) NOT NULL,
  price     DECIMAL NOT NULL,
  detail    TEXT NOT NULL,
  PRIMARY KEY (`id`)
)engine=InnoDB;

DROP TABLE IF EXISTS orders;
CREATE TABLE orders(
  id             int AUTO_INCREMENT,
  order_no       VARCHAR(50) NOT NULL,
  good_id        int NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE (`order_no`)
)engine=InnoDB;

【resources/jdbc.properties】数据库连接信息

mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf-8 
mysql.username=root  #填写你自己的数据库名称
mysql.password=admin #填写你自己的数据库密码

【applicationContext.xml】在resources目录下新建文件spring/applicationContext.xml

​ 这一部分注意点:

​ 分页插件的使用:

​ 4.2版本之前使用com.github.pagehelper.PageHelper

​ 4.2版本以后使用该类com.github.pagehelper.PageInterceptor,

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    <!--开启注解配置-->
    <context:component-scan base-package="com.itcloud.service"/>
    <!--读取资源文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--数据库连接池配置-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${mysql.driver}"/>
        <property name="url" value="${mysql.url}"/>
        <property name="username" value="${mysql.username}"/>
        <property name="password" value="${mysql.password}"/>
    </bean>

    <!--整合mybatis-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--mybatis配置文件的位置,可以不配置,这里主要的目的是进行sql语句的打印-->
        <property name="configLocation" value="classpath:mybatis.config.xml"/>
        <!--*Mapper.xml文件的位置-->
        <property name="mapperLocations" value="classpath:mybatis/*.xml"/>
        <!--整合分页插件-->
        <property name="plugins">
            <array>
                <!--
                     注意点:
                     4.2以后使用该类com.github.pagehelper.PageInterceptor,
                     4.2之前使用com.github.pagehelper.PageHelper
                     官方文档介绍
                         https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
                 -->
                <bean class="com.github.pagehelper.PageInterceptor">
                </bean>
            </array>
        </property>
    </bean>
    <!--扫描mybatis dao层,即*Mapper.java 下面这种方式也行
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itcloud.mapper"/>
    </bean>
    -->

    <mybatis-spring:scan base-package="com.itcloud.mapper"/>

    <!--事务的配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven proxy-target-class="true"/>
</beans>

【resources/mybatis/mybatis.config.xml】

​ 这个xml的作用就是在进行CRUD操作的时候可以在控制台打印出sql语句,这里可以使用日志进行替代,此文件不是必须的

<?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>
    <settings>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>

【Goods.java】

package com.itcloud.pojo;
public class Goods {
    private int id ;
    private String title ;
    private BigDecimal price ;
    private String detail ;
    //getter,setter方法略,这里需要你们自己写或者生成
}

【GoodsMapper.java】

package com.itcloud.mapper;
import com.itcloud.pojo.Goods;
public interface GoodsMapper {
    int insert(Goods goods);
}

resources/mybatis/GoodsMapper.xml】

​ 在这一节里面只是做了一个简单的增加操作,让读者简单认识一下spring整合mybatis的过程

<?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.itcloud.mapper.GoodsMapper">
    <resultMap id="BaseResultMap" type="com.itcloud.pojo.Goods">
        <id property="id" column="id" jdbcType="INTEGER"/>
        <result property="title" column="title" jdbcType="VARCHAR" />
        <result property="price" column="price" jdbcType="DECIMAL" />
        <result property="detail" column="price" jdbcType="VARCHAR" />
    </resultMap>
    <sql id="Base_Column_List">
        id,title,price,detail
    </sql>
    <insert id="insert" parameterType="com.itcloud.pojo.Goods">
        INSERT INTO goods(id,title,price,detail) VALUES (#{id},#{title},#{price},#{detail})
    </insert>
</mapper>

【test/java】建立测试类

package com.itcloud.service;
import java.math.BigDecimal;
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.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.itcloud.pojo.Goods;
@ContextConfiguration("classpath:spring/applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class GoodsServiceTest {
    @Autowired
    private IGoodsService goodsService ;
    @Test
    public void testInsert(){
        Goods goods = new Goods();
        goods.setTitle("篮球");
        goods.setPrice(new BigDecimal("42.14"));
        goods.setDetail("一款适合所有篮球爱好者的篮球,朴素的外观不失优雅");
        int save = goodsService.save(goods);
        System.out.println(save);
    }
}

运行结果:

JDBC Connection [com.mysql.jdbc.JDBC4Connection@a8ef162] will not be managed by Spring
==>  Preparing: INSERT INTO goods(id,title,price,detail) VALUES (?,?,?,?) 
==> Parameters: 0(Integer), 篮球(String), 42.14(BigDecimal), 一款适合所有篮球爱好者的篮球,朴素的外观不失优雅(String)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3de8f619]
1

二、spring整合mybatis逆向工程

这一节我们主要的内容是使用传统的方式进行逆向工程的整合,maven插件的形式

【官方文档】:http://www.mybatis.org/generator/

1.建立子模块spring-mybatis-generator-one

【pom.xml】

​ 这里如要引入了mybatis-generator-maven-plugin这一插件

​ 这里的版本自己定,我在这里因为存在父pom工程,所以没有选择版本;

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <parent>
        <artifactId>spring-root</artifactId>
        <groupId>com.itcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>spring-mybatis-generator-one</artifactId>
    <packaging>war</packaging>
    <name>spring-mybatis-generator-one</name>
    <url>http://maven.apache.org</url>
     <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <springcontext.version>5.0.3.RELEASE</springcontext.version>
    <mybatis.version>3.4.5</mybatis.version>
    <mybatis-spring.version>1.3.1</mybatis-spring.version>
    <pagehelper.version>5.1.2</pagehelper.version>
    <druid.version>1.1.6</druid.version>
    <mysql.version>5.1.40</mysql.version>
    <junit.version>4.12</junit.version>
  </properties>

    <dependencies>
      <!--spring的开发包-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <!--mybatis-->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
      </dependency>
      <!-- 分页插件 -->
      <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>${pagehelper.version}</version>
      </dependency>

      <!-- mybatis-spring -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>${mybatis-spring.version}</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springcontext.version}</version>
      </dependency>
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>${druid.version}</version>
      </dependency>
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
      </dependency>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
      </dependency>
    </dependencies>
    <build>
        <finalName>spring-mybatis-generator-one</finalName>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2.【resources/generatorConfig.xml】建立此文件,文件名必须为generatorConfig.xml

在这里我没有生成example进行复杂的查询,因为example增加了程序的复杂度,还有就是他本身生成的example超级不好用,对于复杂查询还是需要自己进行*Maper.java的扩展

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!--
    配置文件需要注意的地方:因为是maven插件,所以必须使用generatorConfig.xml文件作为文件的名称
-->
<generatorConfiguration>

    <!--定义mysql驱动jar的位置,绝对路径-->
    <classPathEntry
            location="C:\Users\DELL\.m2\repository\mysql\mysql-connector-java\5.1.40\mysql-connector-java-5.1.40.jar"/>


    <!--数据库连接-->
    <context id="mysql" targetRuntime="MyBatis3">
        <commentGenerator >
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/spring?characterEncoding=utf-8"
                        userId="root"
                        password="admin">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--实体类生成策略-->
        <javaModelGenerator targetPackage="com.itcloud.pojo" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
            <!--是否添加构造函数-->
            <property name="constructorPackages" value="true"/>
        </javaModelGenerator>
        <!--*Mapper.xml文件生成策略-->
        <sqlMapGenerator targetPackage="mybatis" targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--dao层生成策略,*Mapper.java生成策略-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.itcloud.mapper" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--此处不生成example的目的是不想用自动生成的example,因为这完全可以自己来控制sql语句,会让程序显得更加简单

        -->
        <table tableName="goods" domainObjectName="Goods"
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <columnOverride column="detail" jdbcType="VARCHAR"/>
        </table>
        <table tableName="orders" domainObjectName="Orders" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>

    </context>
</generatorConfiguration>

3.浏览自动生成的文件

​ 这里只是展示Goods表

【Goods.java】

package com.itcloud.pojo;
import java.math.BigDecimal;
public class Goods {
    private Integer id;
    private String title;
    private BigDecimal price;
    private String detail;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }
    public BigDecimal getPrice() {
        return price;
    }
    public void setPrice(BigDecimal price) {
        this.price = price;
    }
    public String getDetail() {
        return detail;
    }
    public void setDetail(String detail) {
        this.detail = detail == null ? null : detail.trim();
    }
}

【GoodsMapper.java】

package com.itcloud.mapper;
import com.itcloud.pojo.Goods;
public interface GoodsMapper {
    int deleteByPrimaryKey(Integer id);
    int insert(Goods record);
    int insertSelective(Goods record);
    Goods selectByPrimaryKey(Integer id);
    int updateByPrimaryKeySelective(Goods record);
    int updateByPrimaryKey(Goods record);
}

【GoodsMapper.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.itcloud.mapper.GoodsMapper">
  <resultMap id="BaseResultMap" type="com.itcloud.pojo.Goods">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="title" jdbcType="VARCHAR" property="title" />
    <result column="price" jdbcType="DECIMAL" property="price" />
    <result column="detail" jdbcType="VARCHAR" property="detail" />
  </resultMap>
  <sql id="Base_Column_List">
    id, title, price, detail
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from goods
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from goods
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.itcloud.pojo.Goods">
    insert into goods (id, title, price, 
      detail)
    values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{price,jdbcType=DECIMAL}, 
      #{detail,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.itcloud.pojo.Goods">
    insert into goods
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="title != null">
        title,
      </if>
      <if test="price != null">
        price,
      </if>
      <if test="detail != null">
        detail,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="title != null">
        #{title,jdbcType=VARCHAR},
      </if>
      <if test="price != null">
        #{price,jdbcType=DECIMAL},
      </if>
      <if test="detail != null">
        #{detail,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.itcloud.pojo.Goods">
    update goods
    <set>
      <if test="title != null">
        title = #{title,jdbcType=VARCHAR},
      </if>
      <if test="price != null">
        price = #{price,jdbcType=DECIMAL},
      </if>
      <if test="detail != null">
        detail = #{detail,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.itcloud.pojo.Goods">
    update goods
    set title = #{title,jdbcType=VARCHAR},
      price = #{price,jdbcType=DECIMAL},
      detail = #{detail,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

4.进行数据的测试

@ContextConfiguration("classpath:spring/applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class GoodsServiceTest {
    @Autowired
    private IGoodsService goodsService ;

    @Test
    public void testInsert(){
        Goods goods = new Goods();
        goods.setTitle("篮球");
        goods.setPrice(new BigDecimal("42.14"));
        goods.setDetail("一款适合所有篮球爱好者的篮球,朴素的外观不失优雅");
        goodsService.save(goods) ;
    }
    //运行结果
    /**
     JDBC Connection [com.mysql.jdbc.JDBC4Connection@70e38ce1] will not be managed by Spring
     ==>  Preparing: insert into goods (id, title, price, detail) values (?, ?, ?, ?)
     ==> Parameters: null, 篮球(String), 42.14(BigDecimal), 一款适合所有篮球爱好者的篮球,朴素的外观不失优雅(String)
     <==    Updates: 1
     */
    @Test
    public void testDelete(){

        int delete = goodsService.delete(2);
        System.out.println("删除了吗?"+delete);

    }
    //运行结果
    /**
     JDBC Connection [com.mysql.jdbc.JDBC4Connection@70e38ce1] will not be managed by Spring
     ==>  Preparing: delete from goods where id = ?
     ==> Parameters: 1(Integer)
     <==    Updates: 1
     Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4d14b6c2]
     删除了吗?1
     */
}

猜你喜欢

转载自blog.csdn.net/m0_37867405/article/details/79293589