上一篇文章中提到,使用SqlSessionTemplat时需要输入一长串字符串来获取mapper,这种方式IDE不会检查程序的准确性并且很容易出错,所以这篇文章介绍另一种可以避免这种问题,并且也可以使用SqlSessionTemplate的配置方式,那就是MyBatis-Spring团队提供的MapperFactryBean类,通过这个类我们可以配置我们需要的mapper,并通过mapper的类型来获取好,而不需要输入一长串容易出错的字符串。还是使用MyBatis-Spring项目的流程进行介绍:

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

 <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" />
<!-- 配置mybatis -->
<property name="configLocation" value="classpath:mybatis-config2.xml" />
</bean>

上面的配置中,数据源属性指向第一步中配置的dataSource,mybatis配置文件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>

第三步:配置MapperFactoryBean

因为要使用MapperFactoryBean,这里的第三步为配置MapperFactoryBean,跟上一篇中介绍的配置SqlSessionTemplate是同一个步骤,不过上一篇中把它合并到第二步,这里觉得分开会比较清晰些:

 <!-- 通过MapperFactoryBean配置SqlSessionFactory -->
<bean id="productMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 配置mapper接口 -->
<property name="mapperInterface" value="com.hyc.dao.ProductMapper" />
<!-- 配置SqlSessionFactory -->
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
<!-- 如果同时配置sqlSessionTemplate和SqlSessionFactory,将优先使用sqlSessionTemplate -->
<property name="sqlSessionTemplate" ref="sqlSessionTemplate" />
</bean>

这个配置中有三个属性可以配置:

  • mapperInterface:它的值是*mapper.xml对应的接口,即映射器中的接口全限定名;
  • sqlSessionFactory:就是第二步配置的SqlSessionFactory,包含的是数据源和sql文件;
  • sqlSessionTemplate:上一篇文章中介绍过的配置,不再赘述;

注意⚠️:如果同时配置sqlSessionFactory和sqlSessionTemplate,那么前者会被作废,启用后者,所以为了测试,可以将sqlSessionTemplate注释掉。

第四步:创建mapper

其实就是创建映射器,分两步:

1⃣️创建接口

 public interface ProductMapper {

     int insertProduct(Product product);

     int deleteByPrimaryKey(String id);

     int updateByPrimaryKey(Product product);

     List<Product> selectProducts(String name);

 }

2⃣️创建对应的mapper.xml(sql脚本文件)

 <?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>

它的命名空间就是对应接口的全限定名。

至此,所有的配置已经完成,下面来创建单元测试类。

第五步:单元测试

1⃣️创建一个基类,初始化spring配置

 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 TestMapperFactoryBean extends BaseTest {

     @Test
public void testInsert() {
ProductMapper pm = super.context.getBean(ProductMapper.class);
Product product = super.context.getBean(Product.class);
int add = pm.insertProduct(product);
System.out.println(add > 0 ? "插入成功" : "插入失败");
} @Test
public void testDelete() {
ProductMapper pm = super.context.getBean(ProductMapper.class);
int del = pm.deleteByPrimaryKey("9b08ea56-6d92-48fc-844f-190eb6272479");
System.out.println(del > 0 ? "删除成功" : "删除失败");
} @Test
public void testUpdate() {
ProductMapper pm = super.context.getBean(ProductMapper.class);
Product product = super.context.getBean(Product.class);
product.setProductName("测试修改");
product.setProductPrice("修改后价格");
product.setProductType("修改后分类");
int update = pm.updateByPrimaryKey(product);
System.out.println(update > 0 ? "修改成功" : "修改失败");
} @Test
public void testSelect() {
ProductMapper pm = super.context.getBean(ProductMapper.class);
List<Product> pl = pm.selectProducts("T");
System.out.println(pl.size());
}
}

一个一个执行,可进行测试,我的测试结果是都成功的,结果就不贴出来了。

这种方式有一个弊端,就是配置MapperFactoryBean时,mapper要一个一个进行配置,一个项目中的mapper肯定不止一个,所以这种配置难免会增加工作量,显然不利于开发,为此MyBatis提供了另一个类MapperScannerConfigurer,它可以通过扫描的形式去生成对应的mapper,而不需要我们一个一个配置。下一篇将介绍这种扫描配置方式的使用。

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

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

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

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

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

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

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

  4. spring学习(四)spring的jdbcTemplate(增删改查封装)

    Spring的jdbcTemplate操作 1.Spring框架一站式框架 (1)针对javaee三层,每一层都有解决技术 (2)到dao 层,使用 jdbcTemplate 2.Spring对不同的 ...

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

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

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

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

  7. (转)Spring Boot (十五): Spring Boot + Jpa + Thymeleaf 增删改查示例

    http://www.ityouknow.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html 这篇文章介绍如何使用 Jpa 和 ...

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

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

  9. Spring Boot + Jpa + Thymeleaf 增删改查示例

    快速上手 配置文件 pom 包配置 pom 包里面添加 Jpa 和 Thymeleaf 的相关包引用 <dependency> <groupId>org.springframe ...

随机推荐

  1. [JZOJ 5782] 城市猎人

    思路: 并查集按秩合并维护出现时间. 最早连接时间就是树上连接最大值. \(qwq\)我居然把路径压缩和按秩合并打到一个程序里了...OvO #include <bits/stdc++.h> ...

  2. idae for mac部分背景色修改收集

    文章目录 所有字体默认颜色 终端背景色 行数line number背景色 line number颜色 编码区背景色 光标所在行背景色 未被使用的变量.方法或者类 控制台相关 选中文字的背景色 选中和未 ...

  3. Android Drawable 详解(教你画画!)

    参考 1.Android中的Drawable基础与自定义Drawable 2.android中的drawable资源 3.Android开发之Shape详细解读 Drawable分类 No xml标签 ...

  4. 深入分析Service启动、绑定过程

    Service是Android中一个重要的组件,它没有用户界面,可以运行在后太做一些耗时操作.Service可以被其他组件启动,甚至当用户切换到其他应用时,它仍然可以在后台保存运行.Service 是 ...

  5. pip install mysql-python报错1. Unable to find vcvarsall.bat 2 fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory 3.error: command 'mt.exe' failed with exit statu

    最近在安装mysql -python 时报错折腾了半天,通过以下方法解决: 1. pip install mysql-python报错 Unable to find vcvarsall.bat (参考 ...

  6. java_瞬时

    瞬时(Instant): 方法: public class InstantTest01 { public static void main(String[] args){ //静态方法,返回utc上的 ...

  7. 2019-5-15-影子系统让-C++-程序无法运行

    title author date CreateTime categories 影子系统让 C++ 程序无法运行 lindexi 2019-05-15 15:24:35 +0800 2019-05-1 ...

  8. JS流程控制语句 做判断(if语句)if语句是基于条件成立才执行相应代码时使用的语句。语法:if(条件) { 条件成立时执行代码}

    做判断(if语句) if语句是基于条件成立才执行相应代码时使用的语句. 语法: if(条件) { 条件成立时执行代码} 注意:if小写,大写字母(IF)会出错! 假设你应聘web前端技术开发岗位,如果 ...

  9. axios——post请求时把对象obj数据转为formdata格式

    转载自:https://blog.csdn.net/feizhong_web/article/details/80514436  在调用后台接口的时候,上传报名信息,利用axios 的post请求,发 ...

  10. [记]Windows 系统下设置Nodejs NPM全局路径

    Windows下的Nodejs npm路径是appdata,担心安装的node_modules越来越多,导致C盘满,所以参考别人的博文,将node_modules安装的默认目录修改一下. 参考Wind ...