一、Mybatis整合spring

步骤:

  1. 导入相关jar包

    • junit
    • mybatis
    • mysql数据库
    • spring-webmvc
    • aop织入
    • mybatis-spring
    • spring-jdbc(spring的事务管理器,也可以用druid等的代替)
  2. 编写配置文件
  3. 测试
1.1 回忆mybatis
  1. 编写实体类
  2. 编写核心配置文件
  3. 编写接口
  4. 编写Mapper.xml
  5. 测试
1.2 整合方式一

注意版本限制:

  1. dataSource(这里配置使用Spring的数据源替换Mybatis的配置)

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/dailyClick-test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
    <property name="username" value="1111"/>
    <property name="password" value="1111"/>
    </bean>

    注:Mybatis有默认的数据源(连接池),但是是可以替换的

  2. sqlSessionFactory配置

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!-- 绑定配置文件地址和mapper地址-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:com/guan/dao/*.xml"/>
    </bean>

    注意:

    • 需要配置数据源
    • 需要绑定配置文件地址和mapper地址,注意这里的路径使用classpath路径
    • 由于mapper等信息被转移到<bean>中,不能重复配置(如:<mapper>),否则会报错;mybatis-config.xml配置文件通常留<typeAlias><settings>
  3. 与在原来的mybatis不同,整合后需要有一个接口的实现类,且接口的方法需要通过sqlSessionTemplate实现(有利于bean的注册和管理,这个sqlSessioinTemplate是线程安全的)

    sqlSessionTemplate配置

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    注:由于sqlSessionTemplate没有set方法,只有构造函数,所以通过<constructor>标签注入

  4. 实现类:与mybatis元素代码不同,接口类需要实现且接口的方法通过sqlSessionTemplate实现

    public class UserMapperImpl implements UserMapper {
    SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) {
    this.sqlSession = sqlSession;
    } public List<UserBean> getUserList() {
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    return mapper.getUserList();
    }
    }
    <bean id="userMapper" class="com.guan.dao.UserMapperImpl">
    <property name="sqlSession" ref="sqlSession"/>
    </bean>
  5. 测试

    public class MyTest {
    public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapperImpl userMapperImpl = context.getBean("userMapper", UserMapperImpl.class);
    List<UserBean> userList = userMapperImpl.getUserList();
    for (UserBean userBean : userList) {
    System.out.println(userBean);
    }
    }
    }

    注:

    (1).mybatis的配置文件(指的是和spring注册的那一部分),最好通过import引入ApplicationiContext中,这样spring配置文件的结构可以区分开

    (2).xxxTemplate是spring特有的模板类

1.3 整合方式二

注:SqlSessionDaoSupport:抽象类,可以通过SqlSessionFactory获得一个SqlSessionTemplate.所以该方法相对于第一种方法增加了一个抽象类,减少了一个配置SqlSessionTemplate的步骤

  1. 环境搭建:

    接口:

    public interface UserMapper1 {
    List<UserBean> getUserList();
    }

    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.guan.dao.UserMapper1">
    <select id="getUserList" resultType="userBean">
    SELECT * FROM user;
    </select>
    </mapper>

    实体类:

    public class UserMapper1Impl extends SqlSessionDaoSupport implements UserMapper1{
    public List<UserBean> getUserList() {
    return getSqlSession().getMapper(UserMapper1.class).getUserList();
    }
    }
  2. xml配置(在上文的前文的基础上配置)

    <bean id="userMapper1" class="com.guan.dao.UserMapper1Impl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
  3. 测试:

        public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper1Impl userMapperImpl = context.getBean("userMapper1", UserMapper1Impl.class);
    List<UserBean> userList = userMapperImpl.getUserList();
    for (UserBean userBean : userList) {
    System.out.println(userBean);
    }
    }

二、spring中的事物管理

  1. 编程式事务:将事务管理代码嵌到业务方法中控制事务的提交和回滚

    缺点:使业务逻辑中包含额外的事务管理代码

  2. 声明式事物:使用AOP

    (1).搭建环境:

    接口

    public interface UserMapper1 {
    List<UserBean> getUserList();
    void insert(UserBean user);
    void delete(String UId);
    }

    mapper:

    <insert id="insert" parameterType="userBean">
    INSERT INTO user(UId,UName,USet,UAuth,UPassword,UState) VALUES(#{UId},#{UName},#{USet},#{UAuth},#{UPassword},#{UState});
    </insert> <delete id="delete" parameterType="string">
    DELETEs FROM user WHERE UId = #{UId};
    </delete>

    注:可以看到我这里的"DELETEs"是错误的写法

    编写实体类:

    public class UserMapper1Impl extends SqlSessionDaoSupport implements UserMapper1{
    public List<UserBean> getUserList() {
    insert(new UserBean("6666666666","淀真嗣",1,0,"123456",1));
    delete("3180421016");
    return getSqlSession().getMapper(UserMapper1.class).getUserList();
    } public void insert(UserBean user) {
    getSqlSession().getMapper(UserMapper1.class).insert(user);
    } public void delete(String UId) {
    getSqlSession().getMapper(UserMapper1.class).delete(UId);
    }
    }

    注:getUserList中添加了insert和delete方法,且delete方法是错误的.如果没有事务,则插入可以完成;如果有事务,则插入无法完成

    (2).导入事务相关的xml头文件约束,创建DataSourceTransaction对象以开启事务,配置事务通知,结合AOP实现事务的织入

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://47.100.90.132:3306/dailyClick-test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
    <property name="username" value="root"/>
    <property name="password" value="aguan123"/>
    </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!-- bind mybatis-config.xml and userMapper.xml-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:com/guan/dao/*.xml"/>
    </bean> <bean id="userMapper1" class="com.guan.dao.UserMapper1Impl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean> <!-- 配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
    </bean> <!-- 配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <tx:method name="getUserList" propagation="REQUIRED"/>
    </tx:attributes>
    </tx:advice> <!-- 结合AOP织入事务-->
    <aop:config>
    <aop:pointcut id="point" expression="execution(* com.guan.dao.*.*(..))"/>
    <!-- <aop:advisor advice-ref="txAdvice" pointcut-ref="point"/>-->
    </aop:config> </beans>

    注:<tx:method name="getUserList" propagation="REQUIRED"/>的propagation属性表示对这些方法怎样使用事务,如:REQUIRED表示支持当前事务,如果当前没有事务,就新建一个事务 (Default)

    (3).测试

    public class MyTest {
    
        public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper1 userMapperImpl = context.getBean("userMapper1", UserMapper1.class);
    List<UserBean> userList = userMapperImpl.getUserList();
    for (UserBean userBean : userList) {
    System.out.println(userBean);
    }
    }
    }

    注意:由于使用了AOP,这里UserMapper1 userMapperImpl = context.getBean("userMapper1", UserMapper1.class)的返回类型必须为interface类型,而不是实体类型

spring——整合Mybatis的更多相关文章

  1. Spring学习总结(六)——Spring整合MyBatis完整示例

    为了梳理前面学习的内容<Spring整合MyBatis(Maven+MySQL)一>与<Spring整合MyBatis(Maven+MySQL)二>,做一个完整的示例完成一个简 ...

  2. Spring学习总结(五)——Spring整合MyBatis(Maven+MySQL)二

    接着上一篇博客<Spring整合MyBatis(Maven+MySQL)一>继续. Spring的开放性和扩张性在J2EE应用领域得到了充分的证明,与其他优秀框架无缝的集成是Spring最 ...

  3. 分析下为什么spring 整合mybatis后为啥用不上session缓存

    因为一直用spring整合了mybatis,所以很少用到mybatis的session缓存. 习惯是本地缓存自己用map写或者引入第三方的本地缓存框架ehcache,Guava 所以提出来纠结下 实验 ...

  4. 2017年2月16日 分析下为什么spring 整合mybatis后为啥用不上session缓存

    因为一直用spring整合了mybatis,所以很少用到mybatis的session缓存. 习惯是本地缓存自己用map写或者引入第三方的本地缓存框架ehcache,Guava 所以提出来纠结下 实验 ...

  5. spring整合mybatis错误:class path resource [config/spring/springmvc.xml] cannot be opened because it does not exist

    spring 整合Mybatis 运行环境:jdk1.7.0_17+tomcat 7 + spring:3.2.0 +mybatis:3.2.7+ eclipse 错误:class path reso ...

  6. spring 整合Mybatis 《报错集合,总结更新》

    错误:java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldExcepti ...

  7. spring整合mybatis(hibernate)配置

    一.Spring整合配置Mybatis spring整合mybatis可以不需要mybatis-config.xml配置文件,直接通过spring配置文件一步到位.一般需要具备如下几个基本配置. 1. ...

  8. spring 整合 mybatis 中数据源的几种配置方式

    因为spring 整合mybatis的过程中, 有好几种整合方式,尤其是数据源那块,经常看到不一样的配置方式,总感觉有点乱,所以今天有空总结下. 一.采用org.mybatis.spring.mapp ...

  9. Mybatis学习(六)————— Spring整合mybatis

    一.Spring整合mybatis思路 非常简单,这里先回顾一下mybatis最基础的根基, mybatis,有两个配置文件 全局配置文件SqlMapConfig.xml(配置数据源,全局变量,加载映 ...

  10. Spring整合MyBatis 你get了吗?

    Spring整合MyBatis 1.整体架构dao,entity,service,servlet,xml 2..引入依赖 <dependencies> <dependency> ...

随机推荐

  1. 前端语言之js(对比python快速入门)

    昨日内容回顾 浮动 定位 溢出 透明度 模态框 今日内容概要 变量与常量 基本数据类型 数据类型内置方法 函数 常见内置对象 BOM与DOM操作 内容详细 1.变量与常量 # 在JS中声明变量需要使用 ...

  2. 「游记」CSP-S 2021 爆零记

    推荐访问本人自建博客 \(\text{cjwen.top}\) 初赛 之前参加过「难度介于 J 组(基础组)和 S 组(提高组)之间」的 [LGR-(-13) ]SCP 2021 第一轮(初赛)模拟, ...

  3. Solution -「JSOI 2019」「洛谷 P5334」节日庆典

    \(\mathscr{Description}\)   Link.   给定字符串 \(S\),求 \(S\) 的每个前缀的最小表示法起始下标(若有多个,取最小的).   \(|S|\le3\time ...

  4. Note - 多项式乱写

      基础篇戳这里.   大概是记录 @Tiw 的伟大智慧叭.   嗷,附赠一个 全家桶题. 目录 Newton 迭代法 多项式乱算 多项式求逆 多项式 多项式 多项式开根 多项式带余除法 多项式快速幂 ...

  5. HMS Core积极探索基于硬件耳返的功能,帮助唱吧整体唱歌延迟率降低60%

    唱吧的使命是让唱歌更简单.让生活更美好,其布局的K歌业务专注于让曲库更全.音质更好,开创了同框合唱.弹唱等有意思的游戏类K歌玩法.为了让用户拥有更加沉浸的娱乐体验,唱吧与HMS Core积极探索基于硬 ...

  6. dbTable

    标签: <my-Double-Table double-Table="doubleTable" head-List="headList" select-M ...

  7. Devops 开发运维高级篇之Jenkins+Docker+SpringCloud微服务持续集成(上)

    Devops 开发运维高级篇之Jenkins+Docker+SpringCloud微服务持续集成(上) Jenkins+Docker+SpringCloud持续集成流程说明 大致流程说明: 1) 开发 ...

  8. Android Camera2获取预览尺寸和fps范围

    升降摄像头安卓手机刚上市的时候,有些很流行的app刚打开时,前置摄像头就升起来了.好像就是出来看一眼然后又收回去. 虽然我们不调用拍照功能,只是为了获取相机的信息,也是可能让摄像头升起来的. Came ...

  9. Python 中 selenium 库

    目录 selenium 基础语法 一. 环境配置 1. 安装环境 2. 配置参数 3. 常用参数搭配 4. 分浏览器启动 二. 基本语法 1. 元素定位 2. 控制浏览器操作 3. 操作元素的方法 3 ...

  10. 传输层 lcx实现本地端口映射&&内网代理

    如果目标服务器由于防火墙的限制,部分端口(例如3389)的数据无法通过防火墙,可以将目标服务器相应端口的数据透传到防火墙允许的端口(例如53),在目标主机上执行如下命令,就可以直接从远程桌面连接目标主 ...