• sping+maven+mybatis+ehcache续之实现mapper


    配置接着上一篇文章

    新建UserMapper.java和UserMapper.xml

    其中UserMapper.xml的namespace以及文件名要和UserMapper.java一致

    <mapper namespace="com.alibaba.mapper.UserMapper">

    spring增加配置

    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
            <property name="mapperInterface" value="com.alibaba.mapper.UserMapper"/> 
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/> 
    </bean>

    测试类

    package com.alibaba.dao;
    
    import static org.junit.Assert.*;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.alibaba.mapper.UserMapper;
    import com.alibaba.po.User;
    
    public class UserMapperTest {
        
        private ApplicationContext applicationContext;
    
        @Before
        public void setup() throws Exception{
            applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        }
        
        @Test
        public void test() throws Exception{
            UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
            User user = userMapper.getUser(1);
            System.out.println(user);
        }
    
    }


    配置方式2

    启用spring扫描器,将原先的UserMapper Bean注释掉

    <!-- mapper配置 MapperFactoryBean:根据mapper接口生成代理对象 -->
        <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
            <property name="mapperInterface" value="com.alibaba.mapper.UserMapper"/> 
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/> 
        </bean> -->
            
        <!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册 遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录 
            中 自动扫描出来的mapper的bean的id为mapper类名(首字母小写) -->
        <!-- 指定扫描的包名 如果扫描多个包,每个包中间使用半角逗号分隔 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
            <property name="basePackage" value="com.alibaba.mapper"/> 
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> 
        </bean>

    将sqlMapConfig.xml中的扫描包注释掉

    <!-- <package name="com.alibaba.mapper"/>  -->

    测试文件同上。。。。

  • 相关阅读:
    win10安装.net 3.5无法启动服务,原因可能是已被禁用或与其相关联的设备没有启动
    配置SQL用户访问指定表,指定列
    GNU Gettext for Delphi, C++ and Kylix
    Delphi 7 中使用IdUDPServer1和IdUDPClient1控件实现通信检测
    xp不能安装NET Framework4.0解决方法
    基于TCP的Socket连接【Delphi版】
    牛客网优惠码
    GitHub基本操作
    xdb-test
    设置本地yum源
  • 原文地址:https://www.cnblogs.com/tuifeideyouran/p/4581053.html
Copyright © 2020-2023  润新知