Spring4基础 学习笔记(6) ---- Spring与Mybatis整合

Mybatis的主配置文件的DataSource不用注册,在Spring容器中注册
 
mapper动态代理(接口名字对应到映射文件的<insert>等标签的id)替换的是daoimpl。
 
对于Dao的生成:
 
            <!-- 生成Dao的代理对象 -->
            <bean id="StudentDao2" class="org.mybatis.spring.mapper.MapperFactoryBean">
                  <property name="sqlSessionFactory" ref="mySqlSessionFactory"></property>
                  <property name="mapperInterface" value="dao.IStudentDao"></property>
            </bean>
            <!-- 工厂 -->
            <bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                  <property name="configLocation" value="classpath:mybatis-config.xml"></property>
                  <!-- mybatis主配置文件没有数据源,这里注入给sqlSessionFactory -->
                  <property name="dataSource" ref="c3p0Source"></property>
            </bean>
            
            <!-- c3p0数据源 -->
           <bean id="c3p0Source" 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}"/>
          </bean>
         
          <context:property-placeholder location="jdbc.properties"/>
 
 
先前不使用Mapper动态代理的时候:直接new一个DaoImpl,DaoImpl的实现是创建出SqlSession,调用session的insert方法(参数为mapper的id)找到mapper的sql语句
 
这里daoimpl的作用就是  找到sql语句
 
使用mapper动态代理以后,service层用  SqlSession的getMapper方法获得daoImpl的代理
 
 
问题:如果需要多个Dao实现,配置文件会很臃肿
 
解决:将
            <!-- 生成Dao的代理对象 -->
            <bean id="StudentDao2" class="org.mybatis.spring.mapper.MapperFactoryBean">
                  <property name="sqlSessionFactory" ref="mySqlSessionFactory"></property>
                  <property name="mapperInterface" value="dao.IStudentDao"></property>
            </bean>
     改为
            <!-- mapper扫描配置器 -->
            <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                  <property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory"></property>
                  <!-- 这个配置会为指定的基本包的所有接口生成代理对象 -->
                  <property name="basePackage" value="dao"></property>
            </bean>
     由于bean没有id,向service层注入的时候:放接口的简单类名
     
            <bean id="StudentServuce" class="service.IStudentServiceImpl">
                  <property name="dao" ref="IStudentDao"></property>
            </bean>
 
 
问题:把接口IStudentDao改为StudentDao,ref=StudentDao,运行报错 找不到StudentDao
首字母为大写,第二个字母小写会出错!!!,改为全部小写通过
结局:ref改为studentDao就可以通过, 命名的时候需要注意
 
 
 
原文地址:https://www.cnblogs.com/coderlynn/p/8948079.html