MyBatis-Spring--SqlSessionTemplate实现增删改查(批量操作)

 

ssionTemplate是个线程安全的类,每运行一个SqlSessionTemplate时,它就会重新获取一个新的SqlSession,所以每个方法都有一个独立的SqlSession,这意味着它是线称安全的。

第一步:创建spring-mybatis.xml文件并配置数据源

这里使用DBCP数据库连接池的方式:


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5433/postgres" />
        <property name="username" value="postgres" />
        <property name="password" value="postgres" />
        
        <property name="maxActive" value="100" />
        
        <property name="maxIdle" value="5" />
        
        <property name="maxWait" value="10000" />
bean>

第二步:配置SqlSessionFactory


    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource" />
        
        <property name="configLocation" value="mybatis-config2.xml" />
bean>
mybatis-config2.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>
    
    <settings>
        
        <setting name="cacheEnabled" value="true" />
        
        <setting name="lazyLoadingEnabled" value="false" />
        
        <setting name="multipleResultSetsEnabled" value="false" />
        
        <setting name="useColumnLabel" value="true" />
        
        <setting name="useGeneratedKeys" value="false" />
        
        <setting name="autoMappingBehavior" value="PARTIAL" />
        
        <setting name="defaultExecutorType" value="SIMPLE" />
        
        
        
        
        
        <setting name="safeRowBoundsEnabled" value="false" />
        
        <setting name="mapUnderscoreToCamelCase" value="true" />
        
        <setting name="localCacheScope" value="SESSION" />
        
        <setting name="jdbcTypeForNull" value="OTHER" />
        
        <setting name="lazyLoadTriggerMethods" value="equals" />
    settings>
    
    
    <typeAliases>
        
        <package name="com.hyc.pojo" />
        <package name="com.hyc.objectfactory" />
        <package name="com.hyc.bean" />
        <package name="com.hyc.dao" />
    typeAliases>
    
    
    
    <mappers>
        <mapper resource="com/hyc/mapper/ProductMapper.xml" />
    mappers>

configuration>

因为里面配置了映射器,所以下一步需要创建映射器。在创建映射器之前,还要配置SqlSessionTemplate,其配置如下:


    
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
        
        <constructor-arg name="executorType" value="BATCH" />
    bean>

详细配置看注释。注意⚠️:数据源、sqlSessionFactory、sqlSessionTemplate都是配置在spring配置文件spring-mybatis.xml中。

第三步:创建mapper

1.创建接口:ProductMapper.java

public interface ProductMapper {

    int insertProduct(Product product);

    int deleteByPrimaryKey(String id);

    int updateByPrimaryKey(Product product);

    List selectProducts(String name);

}

2.创建mapper:ProductMapper.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.hyc.dao.ProductMapper">
    <resultMap id="BaseResultMap" type="com.hyc.pojo.Product">
        <id column="id" jdbcType="VARCHAR" property="id" />
        <result column="product_name" jdbcType="VARCHAR" property="productName" />
        <result column="product_price" jdbcType="VARCHAR" property="productPrice" />
        <result column="product_type" jdbcType="VARCHAR" property="productType" />
    resultMap>
    <sql id="Base_Column_List">
        id, product_name, product_price, product_type
    sql>

    
    <select id="selectProducts" resultMap="BaseResultMap" parameterType="String">
        select * from product where product_name like concat('%',#{name},'%')
    select>

    
    <insert id="insertProduct" parameterType="com.hyc.pojo.Product">
        insert into product
        (id,
        product_name, product_price,
        product_type)
        values
        (#{id,jdbcType=VARCHAR}, #{productName,jdbcType=VARCHAR},
        #{productPrice,jdbcType=VARCHAR},
        #{productType,jdbcType=VARCHAR})
    insert>

    
    <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
        delete from
        product
        where id = #{id,jdbcType=VARCHAR}
    delete>

    
    <update id="updateByPrimaryKey" parameterType="com.hyc.pojo.Product">
        update product
        set
        product_name = #{productName,jdbcType=VARCHAR},
        product_price =
        #{productPrice,jdbcType=VARCHAR},
        product_type =
        #{productType,jdbcType=VARCHAR}
        where id = #{id,jdbcType=VARCHAR}
    update>
mapper>

在mapper中实现数据库的增删改查操作

 

第四步:

==============================================================

创建单元测试(方法一):通过传统的方式ApplicationContext获得javaBean.

1.先创建一个基类初始化SqlSessionTemplate

public class BaseTest {

    public SqlSessionTemplate template = null;
    ClassPathXmlApplicationContext context = null;

    @Before
    public void before() {
        context = new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml");
        template = context.getBean(SqlSessionTemplate.class);
    }

}

2.创建测试类

public class TestSqlSessionTemplate extends BaseTest {

    @Test
    public void testInsert() {
        Product product = (Product) super.context.getBean("product");
        String sql = "com.hyc.dao.ProductMapper.insertProduct";
        int add = super.template.insert(sql, product);
        System.out.println(add > 0 ? "插入成功" : "插入失败");
    }

    @Test
    public void testDelete() {
        String sql = "com.hyc.dao.ProductMapper.deleteByPrimaryKey";
        int del = super.template.delete(sql, "2");
        System.out.println(del > 0 ? "删除成功" : "删除失败");
    }

    @Test
    public void testUpdate() {
        String sql = "com.hyc.dao.ProductMapper.updateByPrimaryKey";
        Product product = (Product) super.context.getBean("product");
        product.setProductName("test");
        product.setProductPrice("4000");
        product.setProductType("test");
        int update = super.template.update(sql, product);
        System.out.println(update > 0 ? "修改成功" : "修改失败");
    }

    @Test
    public void testSelect() {
        String sql = "com.hyc.dao.ProductMapper.selectProducts";
        List produts = super.template.selectList(sql, "衬");
        System.out.println(produts.size());
    }
}

 

=======================================================================

 

创建单元测试(方法二):通过spring-test包的注解方式(推荐如下)获得javaBean.

 

package com.hyc.test;

import org.junit.runner.RunWith;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.hyc.mapper.ProductMapper;

/**
 * 
 * 在通过spring获取bean实例时,可通过传统的方式ApplicationContext,也可以通过spring-test包的注解方式(推荐如下)
 *    1.导入spring-test包
 *    2.@ContextConfiguration指定Spring的配置文件,即可使用Spring.
 *    3.@Autowired就可以拿到相关Bean
 */
@RunWith(SpringJUnit4ClassRunner.class)        //表示继承了SpringJUnit4ClassRunner类 (spring提供的单元测试类)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestSqlSessionTemplate {
    @Autowired
    private SqlSessionTemplate template;
    
    
    public void testInsert() {
        //...测试方法
        ProductMapper product = template.getMapper(ProductMapper.class);
        //产品的增加方法....
    }
    
}

 

......

 

转 : https://www.cnblogs.com/hellowhy/p/9728862.html

 

你可能感兴趣的:(MyBatis-Spring--SqlSessionTemplate实现增删改查(批量操作))