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



<!--第二步:配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置mybatis -->
<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">
<!-- mybatis的基本配置文件:主要配置基本的上下文参数和运行环境 -->
<configuration>
<!--设置 -->
<settings>
<!--缓存配置的全局开关:如果这里设置成false,那么即便在映射器中配置开启也无济于事 -->
<setting name="cacheEnabled" value="true" />
<!--延时加载的全局开关 -->
<setting name="lazyLoadingEnabled" value="false" />
<!-- 是否允许单一语句返回多结果集 -->
<setting name="multipleResultSetsEnabled" value="false" />
<!-- 使用列标签代替列名,需要兼容驱动 -->
<setting name="useColumnLabel" value="true" />
<!-- 允许JDBC自动生成主键,需要驱动兼容。如果设置为true,则这个设置强制使用自动生成主键,尽管一些驱动不能兼容但仍能正常工作 -->
<setting name="useGeneratedKeys" value="false" />
<!-- 指定MyBatis该如何自动映射列到字段或属性:NONE表示取消自动映射;PARTIAL表示只会自动映射,没有定义嵌套结果集和映射结果集;FULL会自动映射任意复杂的结果集,无论是否嵌套 -->
<setting name="autoMappingBehavior" value="PARTIAL" />
<!-- 配置默认的执行器:SIMPLE是普通的执行器;REUSE会重用预处理语句;BATCH会重用语句并执行批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!--设置超时时间:它决定驱动等待数据库响应的秒数,任何正整数 -->
<!-- <setting name="defaultStatementTimeout" value="25"/> -->
<!--设置数据库驱动程序默认返回的条数限制,此参数可以重新设置,任何正整数 -->
<!-- <setting name="defaultFetchSize" value="100" /> -->
<!-- 允许在嵌套语句中使用分页(RowBounds) -->
<setting name="safeRowBoundsEnabled" value="false" />
<!-- 是否开启自动驼峰命名规则,即从a_example到aExample的映射 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
<!-- 本地缓存机制,防止循环引用和加速重复嵌套循环 -->
<setting name="localCacheScope" value="SESSION" />
<!-- 当没有为参数提供特定JDBC类型时,为空值指定JDBC类型。某些驱动需要指定列的JDBC类型,多数情况直接用一般类型即可,如NULL/VARCHAR/OTHER -->
<setting name="jdbcTypeForNull" value="OTHER" />
<!-- 指定触发延迟加载的方法,如equals/clone/hashCode/toString -->
<setting name="lazyLoadTriggerMethods" value="equals" />
</settings>
<!--类型命名 -->
<!--别名:pojo对象的别名 -->
<typeAliases>
<!-- 对包进行扫描,可以批量进行别名设置,设置规则是:获取类名称,将其第一个字母变为小写 -->
<package name="com.hyc.pojo" />
<package name="com.hyc.objectfactory" />
<package name="com.hyc.bean" />
<package name="com.hyc.dao" />
</typeAliases>
<!--插件 -->
<!-- <plugins /> -->
<!-- 映射器 -->
<mappers>
<mapper resource="com/hyc/mapper/ProductMapper.xml" />
</mappers>

</configuration>


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



<!-- 配置一个可以批量执行的sqlSession-->
<!--配置sqlSessionTemplate:通过带参数的构造方法创建对象 -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 以sqlSessionFactory为参数传入构造函数中 -->
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
<!-- mybatis执行器,取值范围是SIMPLE/REUSE/BATCH三种类型 -->
<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<Product> 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>

<!-- 根据ID删除产品 -->
<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<Product> 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);
//产品的增加方法....
}

}