mybatis-spring整合

一、MyBatis与Spring的集成

在学习mybatis配置时,对于mybatis-config配置的时候我们发现,大致是需要配置三个方面:setting、datasource、mappers

而mybatis的setting往往使用默认配置,所以我们经常配置datasource数据源与mappers映射,但学习spring之后发现,对于datasource的配置交由spring进行管理,所以在spring与mybatis整合后mybatis的配置文件中将不需要配置datasource,mybatis的配置几乎都会在Spring配置之中完成。当然要想要实现spring与mybatis的整合,其中最重要的就是 mybatis-spring.jar 包

  • mybatis-spring会用于帮助你将 MyBatis 代码无缝地整合到 Spring 中。
  • Spring 将会加载必要的 MyBatis 工厂类和 Session 类
  • 提供一个简单的方式来注入 MyBatis 数据映射器和 SqlSession 到业务层的 bean 中。
  • 方便集成 Spring 事务
  • 翻译 MyBatis 的异常到 Spring 的 DataAccessException 异常(数据访问异常)中。

Mybatis-Spring 兼容性,我们在选择Spring、MyBatis以及mybatis-spring时,应注意版本之间的兼容性
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aIhmf0xd-1601253473099)(img/20200925162004618-1601173028071.png)]

二、spring与mybatis快速整合

①导入spring与mybatis相应坐标
  <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><!--定义Spring版本号--><org.springframework.version>4.3.18.RELEASE</org.springframework.version></properties><dependencies><!-- 单元测试相关依赖 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${org.springframework.version}</version></dependency><!-- spring必要依赖 --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${org.springframework.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${org.springframework.version}</version></dependency><!-- spring aop织入依赖 --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.13</version></dependency><!-- mysql驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency><!-- 数据库连接池 --><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.29</version></dependency><!-- mybatis相关依赖 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.6</version></dependency><!-- mybatis与spring对接依赖 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.2</version></dependency></dependencies>
②创建数据库连接配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root# 初始化大小,最小,最大
initialSize=10
minIdle=6
maxActive=50
③创建mybatis配置文件

mybatis文件与之前不同,之前在mybatis-config.xml中配置数据库连接的,现在要把这些放在spring的配置文件中,所以mybatis配置文件中只写setting配置

<?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="true"/><setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/><setting name="aggressiveLazyLoading" value="false"/><!-- 缓冲区配置 --><setting name="localCacheScope" value="SESSION"/></settings><!--<environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url"value="jdbc:mysql://localhost:3306/test" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment></environments> --><!-- 映射文件的配置<mappers><package name="com.dao" /></mappers> -->
</configuration>
④创建spring配置文件

2)spring配置头文件与约束地址

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

2)spring注解开发

    <!-- 开启spring 注解扫描 --><context:component-scan base-package="com.yunhe"/>

3)导入properties配置文件

    <!-- 加载类路径下的properties配置文件 --><context:property-placeholder location="classpath:jdbc.properties"/>

4)dataSource数据源配置

     <!-- datasource数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="user" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/><property name="initialPoolSize" value="${initialSize}"/><property name="minPoolSize" value="${minIdle}"/><property name="maxPoolSize" value="${maxActive}"/></bean>

5)sqlSessionFactory数据会话工厂配置

 <!-- 配置SqlSessionFactory对象 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 注入数据库连接池 --><property name="dataSource" ref="dataSource"/><!-- 配置mybatis配置文件 --><property name="configLocation" value="classpath:mybatis.xml"/><!-- 配置mapper映射文件 --><property name="mapperLocations" value="classpath:mapper/*.xml"/></bean>

6)mapper接口配置

    <!-- mybatis.spring自动映射,DAO接口所在包名,Spring会自动查找其下的类 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.yunhe.mapper" /></bean>

7)事务管理器

    <!--平台事务管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean>

8)设置事务扫描

    <!-- 开启事务控制的注解支持 --> <tx:annotation-driven transaction-manager="transactionManager" />
⑤根据配置文件创建相应的包、接口、实体类

Account

package com.yunhe.pojo;
public class Account {private String name;private double money;public String getName() {return name;}public void setName(String name) {this.name = name;}public double getMoney() {return money;}public void setMoney(double money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"name='" + name + '\'' +", money=" + money +'}';}
}

AccountMapper

package com.yunhe.mapper;
import com.yunhe.pojo.Account;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AccountMapper {public List<Account> selectAll();
}
⑥书写mapper的sql映射配置文件

AccountMapper.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.yunhe.mapper.AccountMapper"><select id="selectAll" resultType="com.yunhe.pojo.Account">select * from account</select>
</mapper>
⑦书写测试代码
import com.yunhe.mapper.AccountMapper;
import com.yunhe.pojo.Account;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class T {@Testpublic void asd(){ApplicationContext ac=new ClassPathXmlApplicationContext("spring.xml");AccountMapper accountMapper = (AccountMapper) ac.getBean("accountMapper");List<Account> accounts = accountMapper.selectAll();System.out.println(accounts);}
}

三、mybatis-spring整合jar包功能

①SqlSessionFactoryBean

在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory 的。 而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来创建。
要创建工厂 bean,将下面的代码放到 Spring 的 XML 配置文件中:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" />
</bean>

1)DataSource
SqlSessionFactory 有一个唯一的必要属性:用于 JDBC 的 DataSource。这可以是任意的 DataSource 对象,它的配置方法和其它 Spring 数据库连接是一样的。

2)configLocation
一个常用的属性是 configLocation,它用来指定 MyBatis 的 XML 配置文件路径。它在需要修改 MyBatis 的基础配置非常有用。通常,基础配置指的是 或 元素。
需要注意的是,这个配置文件并不需要是一个完整的 MyBatis 配置。确切地说,任何环境配置(),数据源()和 MyBatis 的事务管理器()都会被忽略。SqlSessionFactoryBean 会创建它自有的 MyBatis 环境配置(Environment),并按要求设置自定义环境的值。

如果 MyBatis 在映射器类对应的路径下找不到与之相对应的映射器 XML 文件,那么也需要配置文件。这时有两种解决办法:第一种是手动在 MyBatis 的 XML 配置文件中的 部分中指定 XML 文件的类路径;第二种是设置工厂 bean 的 mapperLocations 属性。

3)mapperLocations
mapperLocations 属性接受多个资源位置。这个属性可以用来指定 MyBatis 的映射器 XML 配置文件的位置。属性的值是一个 Ant 风格的字符串,可以指定加载一个目录中的所有文件,或者从一个目录开始递归搜索所有目录。比如:

    <!-- 配置SqlSessionFactory对象 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 注入数据库连接池 --><property name="dataSource" ref="dataSource"/><!-- 配置mybatis配置文件 --><property name="configLocation" value="classpath:mybatis.xml"/><!-- 配置mapper映射文件 --><property name="mapperLocations" value="classpath:mapper/*.xml"/></bean>
②MapperScannerConfigurer

basePackage
MapperScannerConfigurer:有一个重要的属性basePackage用于扫描映射指定包下所有的mapper映射接口,mybatis执行时会与已经加载的mapper对应的xml进行映射调用相应的方法执行sql语句返回结果

   <!-- mybatis.spring自动映射,DAO接口所在包名,Spring会自动查找其下的类 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.yunhe.mapper" /></bean>

四、mybatis-spring整合配置文件注意项

①导入properties配置文件时使用class相对路径注意包的层级关系
    <!-- 导入properties配置文件 --><context:property-placeholder location="classpath:jdbc.properties"/>
②spring注解扫描管理实例对象位置
    <!-- 开启spring 注解扫描 --><context:component-scan base-package="com.yunhe"/>
③sqlsessionfactory会话工厂对象注入

1)注入dataSource ref应与创建dataSource id一致

2)mybatis配置文件使用class相对路径注意包的层级关系

3)如果仅使用mybatis注解开发(不书写mapper.xml时)不需要配置mapper映射

<!-- 配置SqlSessionFactory对象 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 注入数据库连接池 --><property name="dataSource" ref="dataSource"/><!-- 配置mybatis配置文件 --><property name="configLocation" value="classpath:mybatis.xml"/><!-- 配置mapper映射文件 --><property name="mapperLocations" value="classpath:mapper/*.xml"/></bean>
④mapper接口自动映射扫描包虽然也会扫描子包但尽量不要
 <!-- mybatis.spring自动映射,DAO接口所在包名,Spring会自动查找其下的类 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.yunhe.mapper" /></bean>

阿里云短信接口

阿里云短信服务(Short Message Service)是阿里云为用户提供的一种通信服务的能力。

支持向国内和国际快速发送验证码、短信通知和推广短信,服务范围覆盖全球200多个国家和地区。国内短信支持三网合一专属通道,与工信部携号转网平台实时互联。电信级运维保障,实时监控自动切换,到达率高达99%。完美支撑双11期间20亿短信发送,6亿用户触达。

  <dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.5.3</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-dysmsapi</artifactId><version>1.0.0</version></dependency>
package com.yunhe.service.test;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;import java.util.Random;public class SendSms {private static final String AccessKeyId = "";//你的accessKeyIdprivate static final String AccessKeySecret = "";//你的accessKeySecretprivate static final String SignName = "";//使用的签名private static final String TemplateCode = "";//发送短信使用的模板private static IAcsClient acs = null;//服务对象private static SendSmsRequest req = new SendSmsRequest();//短信发送请求对象static {IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AccessKeyId, AccessKeySecret);acs = new DefaultAcsClient(profile);}//随机生成指定位数验证码public static StringBuffer randomCode(int number){//验证码内容集final char[] CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};StringBuffer stringBuffer=new StringBuffer();Random r=new Random();for(int i=0;i<number;i++){stringBuffer.append(CHARS[r.nextInt(CHARS.length)]);}return stringBuffer;}//自定义发送方法public static boolean sendCode(String mobile, String code) throws ClientException {req.setPhoneNumbers(mobile);//设置接收短信手机号req.setSignName(SignName);//设置使用签名req.setTemplateCode(TemplateCode);//设置使用通知模板idreq.setTemplateParam("{\"code\":\"" + code + "\"}");//设置请求参数  以json字符串形式与模板一致SendSmsResponse res = acs.getAcsResponse(req);//向服务器发送请求System.out.println("res code: " + res.getCode());//响应状态码System.out.println("res message: " + res.getMessage());//响应信息if (res.getCode() == null || !res.getCode().equals("OK")) {System.out.println(res.getMessage());return false;}return true;}//自定义发送方法public static boolean sendCode1(String mobile, String code,String ...str) throws ClientException {req.setPhoneNumbers(mobile);//设置接收短信手机号req.setSignName(SignName);//设置使用签名req.setTemplateCode(TemplateCode);//设置使用通知模板idreq.setTemplateParam( "{\"username\":\"帅哥\",\"number\":\"17600222237\",\"address\":\"中国靠山屯\"}");//设置请求参数  以json字符串形式与模板一致SendSmsResponse res = acs.getAcsResponse(req);//向服务器发送请求System.out.println("res code: " + res.getCode());//响应状态码System.out.println("res message: " + res.getMessage());//响应信息if (res.getCode() == null || !res.getCode().equals("OK")) {System.out.println(res.getMessage());return false;}return true;}public static void main(String[] args) throws ClientException {System.out.println(sendCode1("13633840555,17600222237,18749395872",randomCode(6).toString()));}
}

: " + res.getCode());//响应状态码
System.out.println("res message: " + res.getMessage());//响应信息
if (res.getCode() == null || !res.getCode().equals(“OK”)) {
System.out.println(res.getMessage());
return false;
}
return true;
}
public static void main(String[] args) throws ClientException {

    System.out.println(sendCode1("13633840555,17600222237,18749395872",randomCode(6).toString()));
}

}

Spring、mybatis整合,阿里短信接口相关推荐

  1. tp6框架结合阿里短信接口发送短信并记录redis

    tp6框架结合阿里短信接口发送短信并记录redis 1> 开通阿里云短信服务 2> 安装redis服务 3>config配置文件 创建sms.php 文件,配置阿里云短信信息 ret ...

  2. Spring boot简单的接入阿里短信接口

    准备工作如下: 我们需要在阿里云上开通短信服务,这里可以买资源包,也可以自己充值; 创建短信验证签名,签名需要阿里后台审核,一般2小时左右; 创建短信模板; 在用户头像下菜单,(在AccessKey管 ...

  3. 2023-01-16 阿里SMS短信接口使用

    用户注册-使用阿里短信接口和Redis 文章目录 用户注册-使用阿里短信接口和Redis 步骤 1.导入依赖 2.redis属性配置文件 3.spring集成redis配置文件 4.短信接口属性配置文 ...

  4. 阿里云短信接口开发实践(Java)

    随着互联网的兴起,各行各业的需求都在不断的增加.随着业务的扩大,企业给用户发送短信验证码的业务,也是如火如荼.在这里,calvin给各位开发者推荐阿里云短信平台.原因有二:1.接入较简单,开发成本低 ...

  5. thinkphp5+阿里短信发送验证码

    一.申请阿里短信接口,开通服务,申请AccessKey ID和Access Key Secret 二.申请短信发送模板 三.在thinkphp5中的config文件中添加一下配置 //短信配置'SMS ...

  6. 云片短信php接口_php与阿里云短信接口接入

    使用阿里云短信API,需要在控制台获取以下必要参数,其中需要自己手机验证+官方审核多次,尤其审核需要保持耐心. 1. accessKeyId 相当于你的个人账户密钥: 2. accessKeySecr ...

  7. WordPress主题zibll子比主题+新增阿里云短信/腾讯云/短信宝/风吹雨短信接口

    介绍: WordPress主题zibll子比主题–版本V5.1版 新增用户登录/注册/找回密码页面及多项对应设置(自动生成无需设置) 新增默认登录为弹框或页面的选项 新增登录框左侧图像显示功能(支持多 ...

  8. 阿里云短信接口,函数方法

    调用方法:sendmsg(15112211211) /** * 方法功能:新版发送短信接口 * 开发时间:16-7-26 下午2:29 * $phone :需要发送目的地手机号 * $content; ...

  9. PHP 阿里云短信接口调用及检测验证码

    发送短信 发送短信先要在阿里云注册签名及code模板,获取AccessKeyId和AccessKeySecret值 <?php /*** Created by PhpStorm.* User: ...

最新文章

  1. 如何选择容器注册表?这里给出九个选项
  2. 【渝粤教育】电大中专混凝土结构作业 题库
  3. 电子工业出版社博文视点在2010年系统架构师大会上集锦
  4. c语言void nzp,二级C语言考试辅导教程第五章:函数[5]
  5. Android消息推送(Android Push Notification)
  6. 静态修饰词static以及图解分析
  7. 遗传算法学习及matlab代码
  8. Ubuntu18.04安装可视化软件Pyviz
  9. dubbo源码解析之服务发布与注册
  10. Eucalyptus云平台搭建
  11. 网页视频html转换ppt,ppt转web ppt可以转换为视频文件?
  12. SystemTap笔记03 stap的event和handler
  13. 6 RFID的ISOIEC标准
  14. 多看电纸书如何安装第三方软件(如微信读书、梅糖桌面、Eink桌面等)
  15. 工业镜头的主要参数与选型
  16. qq出示测试软件语音聊天,QQ语音时语音测试时可以听到声音,播放测试语音时听不到,也听不到好友发来的语音,请问怎么处理...
  17. Arduino 控制 DS1302 时钟芯片
  18. 从gitlab迁移到极狐gitlab的方法 #JIHULAB101
  19. windows 2012下安装.NET框架时出现组件的文件跟组件清单中的验证信息不匹配,无法安装
  20. hp扫描无法选择发送到计算机,HP Officejet Pro 8600打印机无法使用扫描到计算机的功能...

热门文章

  1. java实现欢乐找茬,欢乐找茬乐翻天红包版
  2. cisco 3560交换机bin升级
  3. 固态硬盘的SLC、MLC、TLC和QLC的区别
  4. 5 款 Gmail 的开源替代品
  5. pageInfo类属性含义小结
  6. MATLAB 透镜成像特征曲线及分析(一)
  7. 解决方案指导------匹配(Matching)(2)
  8. 从太极助手事件看移动应用市场
  9. 加密算法解析三:SM3
  10. win7窗口任务栏图标显示异常