MyBatis-Spring(二)--SqlSessionTemplate实现增删改查
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实现增删改查的更多相关文章
- MyBatis之二:简单增删改查
这一篇在上一篇的基础上简单讲解如何进行增删改查操作. 一.在mybatis的配置文件conf.xml中注册xml与注解映射 <!-- 注册映射文件 --> <mappers> ...
- SpringBoot+Mybatis+Maven+MySQL逆向工程实现增删改查
SpringBoot+Mybatis+MySQL+MAVEN逆向工程实现增删改查 这两天简单学习了下SpringBoot,发现这玩意配置起来是真的方便,相比于SpringMVC+Spring的配置简直 ...
- SQL Server -- 回忆笔记(二):增删改查,修改表结构,约束,关键字使用,函数,多表联合查询
SQL Server知识点回忆篇(二):增删改查,修改表结构,约束,关键字使用,函数,多表联合查询 1. insert 如果sql server设置的排序规则不是简体中文,必须在简体中文字符串前加N, ...
- Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例
Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例 一.快速上手 1,配置文件 (1)pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 ...
- Ecmall二次开发-增删改查操作
Ecmall二次开发-增删改查操作 Model目录includes/models 自己添加需要的model class OrdercomplainModel extends BaseModel //类 ...
- 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-2.使用Mybatis注解开发视频列表增删改查
笔记 2.使用Mybatis注解开发视频列表增删改查 讲解:使用Mybatis3.x注解方式 增删改查实操, 控制台打印sql语句 1.控制台打印sql语句 ...
- Mybatis之基于XML的增删改查
这里先吐槽下,写的半天的东西,IE浏览器弹出调试窗口导致写的东西全部没保存,搞得我还要重新用谷歌写,思路全没了,fuck. 前面学习了下spring的DAO层,说起DAO层,那ORM肯定是少不了的,O ...
- spring boot2+jpa+thymeleaf增删改查例子
参考这遍文章做了一个例子,稍微不同之处,原文是spring boot.mysql,这里改成了spring boot 2.Oracle. 一.pom.xml引入相关模块web.jpa.thymeleaf ...
- mybatis学习(五)——增删改查及自增主键的获取
一.mybatis的增删改查 1.修改hotelMapper接口 package com.pjf.mybatis.dao; import com.pjf.mybatis.po.Hotel; publi ...
随机推荐
- 关于radio选中或者反选
关注点:一.attr()和prop()的区别 <!DOCTYPE html> <html> <head> <title>JavaScript对文字按 ...
- ceph-pg
版本:mimic https://192.168.1.5:8006/pve-docs/chapter-pveceph.html#pve_ceph_osds As a rule of thumb, fo ...
- dubbo超时原理以及解决方案
dubbo超时原理以及解决方案 本篇主要记录dubbo中关于超时的常见问题,实现原理,解决的问题 超时问题 为了检查对dubbo超时的理解,尝试回答如下几个问题,如果回答不上来或者不确定那么说明此处需 ...
- Python Numpy 矩阵级基本操作(1)
NumPy的操作介绍 import numpy as np #导入numpy包,简写为np print "Generate 1*10 matrix" a=np.arange(1,1 ...
- 力扣算法题—147Insertion_Sort_List
Sort a linked list using insertion sort. A graphical example of insertion sort. The partial sorted l ...
- linux中errno及perror的应用
1 perror 定义在头文件<stdlib.h>中 void perror(const char *s);函数说明 perror ( )用 来 将 上 一 个 函 数 发 生 错 误 的 ...
- 集中式日志系统 ELK 协议栈详解
简介 在我们日常生活中,我们经常需要回顾以前发生的一些事情:或者,当出现了一些问题的时候,可以从某些地方去查找原因,寻找发生问题的痕迹.无可避免需要用到文字的.图像的等等不同形式的记录.用计算机的术语 ...
- Spring学习笔记(4)——IoC学习
IoC理论的背景我们都知道,在采用面向对象方法设计的软件系统中,它的底层实现都是由N个对象组成的,所有的对象通过彼此的合作,最终实现系统的业务逻辑. 图1:软件系统中耦合的对象 如果我们打开机械式手表 ...
- go中的string操作
strings 判断字符串s是否以prefix开头 strings.HasPrefix(s string,preffix string) bool: 判断字符串s是否以suffix结尾 stirngs ...
- shell专用参数变量