zoukankan      html  css  js  c++  java
  • MyBatis的Dao层注入SqlSession

      有点坑爹,以前没用过Mybatis,最近才用,而且一直用Mybatis推荐的接口映射的方式,但是今天有人告诉我接口方式用得少,大多还是采用从配置文件里面读sql的方式,当然接口也是类似的,都是利用mapper.xml。

      于是就想把这东西整合进来,当进行dao的时候发现一个小问题,sqlSession怎么注入进来的问题,以前Hibernate的的习惯用sessionFactory的openSession()方法,但是每个方法都要open一下,麻烦,就想能不能直接把sqlSession通过注解注入进来,有下面这三个类都实现了这个接口:

      

    我估计这三个类都差不多,个人估计是功能呢和支持上或者线程同步上面的差别,应该都能生成一个SqlSession实例让我在dao层中运用,打开DefaultSqlSession这个类,里面的几个属性没看懂,于是放弃这个类了;在打开SqlSessionManager这个类,发现构造方法都跟输入流有点关系,我怀疑是根据配置文件之类的方式来实例化,又放弃了;在打开SqlSessionTemplate这个类,发现构造方法只和sqlSessionFactory有关系,感觉有点像了,因为容器里面本来就有sqlSessionFactory,所以可以直接实例化,他的构造方法:

      public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
      }

    于是在spring配置文件中加入下面配置,通过构造方法来实例化。

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

    然后在dao层注入:

    @Repository
    public class ArticleDaoImpl implements ArticleDao {
    
        @Resource
        private SqlSession sqlSession;
    }

    随便找了个类测了下通过了,说明这样做是可行的,然后上网查了下看别人是怎么做的,有人说到dao继承SqlSessionDaoSupport这个类,这个类里面包含了有sqlSession,于是看了下这个类的源码,发现这个类里面的sqlSession其实就是SqlSessionTemplate类的实力,跟上面一样的,

      public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        if (!this.externalSqlSession) {
          this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
        }
      }
    
      public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSession = sqlSessionTemplate;
        this.externalSqlSession = true;
      }

    也就没去研究这个类到底有什么用,我个人是有个不好的癖好,除非万不得已我不太喜欢去继承某个类,感觉一旦继承了就加入了耦合,有这么个毛病,所以就这样子了,不知道SqlSession的其他两个实现有什么特点,也不清楚网上说继承这个SqlSessionDaoSupport有什么特点。唉~~,以后再看看吧。

  • 相关阅读:
    Vue 组件封装发布到npm 报错 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
    SpringBoot thymeleaf模板版本,thymeleaf模板更换版本
    SpringBoot application.properties (application.yml)优先级从高到低
    SpringBoot Cmd运行Jar文件指定active文件的命令如下
    Linux各文件夹的作用
    spring + Mybatis + pageHelper + druid 整合源码分享
    MyEclipse weblogic Deploy Location项目名称不正确解决方案
    Mybatis整合通用Dao,Mybatis整合通用Mapper,MyBatis3.x整合通用 Mapper3.5.x
    An internal error occurred during: "Launching xxx on WebLogic10.x".
    Spring集成Mybatis,spring4.x整合Mybatis3.x
  • 原文地址:https://www.cnblogs.com/dreamroute/p/3893422.html
Copyright © 2011-2022 走看看