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

上一篇文章已经介绍过MyBatis-Spring项目的搭建过程,本节按照前面介绍的流程,通过SqlSessionTemplate实现数据库的增删改差。

第一步:创建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,其配置如下:

 <!--配置sqlSessionTemplate:通过带参数的构造方法创建对象 -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 以sqlSessionFactory为参数传入构造函数中 -->
<constructor-arg ref="sqlSessionFactory" />
<!-- mybatis执行器,取值范围是SIMPLE/REUSE/BATCH三种类型 -->
<constructor-arg 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中实现数据库的增删改差操作

第四步:创建单元测试:

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());
}
}

下面一个一个执行查看测试结果,结果我就不贴出来了,肯定是要成功的结果,下面说一个测试过程中的问题吧:就是我插入、删除、更新都成功了,但返回的不是成功的条数,而是个负数-2147482646,经过查阅资料,网上都说是因为处理器类型导致的,我在配置中设置的mybatis处理器类型是BATCH,也就是批量,当我把它改成SIMPLE之后就成功了。

总结:其实从上测试中来看,使用SqlSessionTemplate获取mapper中的sql时想需要传一个字符串,这个字符串由mapper文件中的命名空间+方法ID组成,当使用字符串时IDE无法检查代码的逻辑性,而且也很容易出错,所以其实这种用法已经被更好的方法替代了,开发过程中也很少会使用这种方式,下一篇将会介绍更好的实现方式。

MyBatis-Spring(二)--SqlSessionTemplate实现增删改查的更多相关文章

  1. MyBatis之二:简单增删改查

    这一篇在上一篇的基础上简单讲解如何进行增删改查操作. 一.在mybatis的配置文件conf.xml中注册xml与注解映射 <!-- 注册映射文件 --> <mappers> ...

  2. SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查

    SpringBoot+Mybatis+MySQL+MAVEN逆向工程实现增删改查 这两天简单学习了下SpringBoot,发现这玩意配置起来是真的方便,相比于SpringMVC+Spring的配置简直 ...

  3. SQL Server -- 回忆笔记(二):增删改查,修改表结构,约束,关键字使用,函数,多表联合查询

    SQL Server知识点回忆篇(二):增删改查,修改表结构,约束,关键字使用,函数,多表联合查询 1. insert 如果sql server设置的排序规则不是简体中文,必须在简体中文字符串前加N, ...

  4. Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例

    Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例 一.快速上手 1,配置文件 (1)pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 ...

  5. Ecmall二次开发-增删改查操作

    Ecmall二次开发-增删改查操作 Model目录includes/models 自己添加需要的model class OrdercomplainModel extends BaseModel //类 ...

  6. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-2.使用Mybatis注解开发视频列表增删改查

    笔记 2.使用Mybatis注解开发视频列表增删改查     讲解:使用Mybatis3.x注解方式 增删改查实操, 控制台打印sql语句              1.控制台打印sql语句      ...

  7. Mybatis之基于XML的增删改查

    这里先吐槽下,写的半天的东西,IE浏览器弹出调试窗口导致写的东西全部没保存,搞得我还要重新用谷歌写,思路全没了,fuck. 前面学习了下spring的DAO层,说起DAO层,那ORM肯定是少不了的,O ...

  8. spring boot2+jpa+thymeleaf增删改查例子

    参考这遍文章做了一个例子,稍微不同之处,原文是spring boot.mysql,这里改成了spring boot 2.Oracle. 一.pom.xml引入相关模块web.jpa.thymeleaf ...

  9. mybatis学习(五)——增删改查及自增主键的获取

    一.mybatis的增删改查 1.修改hotelMapper接口 package com.pjf.mybatis.dao; import com.pjf.mybatis.po.Hotel; publi ...

随机推荐

  1. CountDownLatch和CyclicBarrier区别

    CountDownLatch : 一个线程(或者多个), 等待另外N个线程完成某个事情之后才能执行. CyclicBarrier : N个线程相互等待,任何一个线程完成之前,所有的线程都必须等待. 倒 ...

  2. Win10+CentOS7双系统引导修复

    在有Win10的系统下安装了CentOS7后,CentOS7的引导并不会像CentOS6一样自动加载入Win10驱动.难道是grub2不能引导Win驱动?查了一下资料原来是CentOS不能识别Win1 ...

  3. Area的使用

    本文转自-->王亮的博客文章[ASP.NET MVC 小牛之路]08 - Area 使用 文章引导 MVC路由解析---IgnoreRoute MVC路由解析---MapRoute MVC路由解 ...

  4. spark sql数据源--hive

    使用的是idea编辑器 spark sql从hive中读取数据的步骤:1.引入hive的jar包 2.将hive-site.xml放到resource下 3.spark sql声明对hive的支持 案 ...

  5. 9-vim-移动命令-04-利用标记返回之前小编辑的代码位置

    标记 在开发时,某一块代码可能需要处理,例如编辑或重看. 此时使用命令模式(普通模式)下使用m增加一个标记,这样可以在需要时快速地跳回来或者执行其他编辑操作.   标记名称可以是a~z或者A~Z之间的 ...

  6. 在Ubuntu中安装配置java后运行java -version时提示二进制文件不能执行

    因为jdk安装包有问题,试试32位的

  7. python 根据余弦定理计算两边的夹角

    前面写过C#的. import numpy def GetAngle(sta_point, mid_point, end_point): ma_x = sta_point.X-mid_point.X ...

  8. 函数高阶(函数,改变函数this指向,高阶函数,闭包,递归)

    一.函数的定义方式 1.函数声明方式 function  关键字(命名函数) 2.函数表达式(匿名函数) 3.new  Function( ) var  fn = new  Function(‘参数1 ...

  9. VS2013+Opencv3.3配置教程

    转载自: https://blog.csdn.net/u014797226/article/details/78283873?locationNum=5&fps=1 参考博文1: 操作环境: ...

  10. nodejs 进阶:图片裁剪

    demo 图片: 效果: var fs = require('fs'); var gm = require('gm'); gm("./不饿.jpg").crop(100,100,2 ...