spring mybatis获取mapper的方式有哪些

2023-05-18,,

本篇内容介绍了“spring mybatis获取mapper的方式有哪些”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

    spring-mybatis获取mapper方式汇总

    项目背景:

    pojo下面有一个user实体类

    Dao包下面写了usermapper.xml 和usermapper.interface,其中只有一个方法查询数据库中所有的用户。

    1.用实现类获取这个用户

    <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/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </bean>
    
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
    	
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
    
    	<!--注册实现类usermapperimpl-->
        <bean id="userMapper" class="com.kuang.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>

    实现类usermapperImpl:

    public class UserMapperImpl implements UserMapper {
        private SqlSessionTemplate sqlSession;
    
        public List<User> selectAllUser() {
            return sqlSession.getMapper(UserMapper.class).selectAllUser();
        }
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    }

    test测试:

    @Test
        public void test2(){
            ApplicationContext app = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapperImpl userMapper = app.getBean(UserMapperImpl.class);
            List<User> users = userMapper.selectAllUser();
            for (User user : users) {
                System.out.println(user);
            }
        }

    2.SqlSessionDaoSupport获取

    public class UserMapperImpl1 extends SqlSessionDaoSupport implements UserMapper {
        public List<User> selectAllUser() {
            return getSqlSession().getMapper(UserMapper.class).selectAllUser();
        }
    }

    bean的注册:

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
    
    <bean id="userimpl1" class="com.kuang.mapper.UserMapperImpl1">
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>

    3.MapperFactoryBean

    <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/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
        
    <bean id="userimpl" class="org.mybatis.spring.mapper.MapperFactoryBean">
            <property name="mapperInterface" value="com.kuang.mapper.UserMapper"/>
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>

    测试:

     @Test
        public void test3(){
            ApplicationContext app = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapper userMapper = app.getBean(UserMapper.class);
             // UserMapper userMapper = app.getBean("userimpl");
            List<User> users = userMapper.selectAllUser();
            for (User user : users) {
                System.out.println(user);
            }
        }

    在使用这个MapperFactoryBean方式的时候,通过app有两种方式获取bean,一种是id然后强转,另一种是接口的类型class。

    4.MapperScannerConfigurer

    xml配置

    <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/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </bean>
    
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.kuang.mapper"/>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>

    test:

    @Test
        public void test4(){
            ApplicationContext app = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapper bean = app.getBean(UserMapper.class);
            for (User user : bean.selectAllUser()) {
                System.out.println(user);
            }
        }

    mybatis的mapper注解

    从mybatis3.4.0开始加入了@Mapper注解,目的就是为了不再写mapper映射文件(那个xml写的是真的无语。。。)。很恶心的一个事实是源码中并没有对于这个注解的详细解释

    在 Spring 程序中,Mybatis 需要找到对应的 mapper,在编译的时候动态生成代理类,实现数据库查询功能,所以我们需要在接口上添加 @Mapper 注解。

    @Mapper
    public interface UserDao {
        ...
    }

    但是,仅仅使用@Mapper注解,我们会发现,在其他变量中依赖注入,IDEA 会提示错误,但是不影响运行(亲测~)。

    因为我们没有显式标注这是一个 Bean,IDEA 认为运行的时候会找不到实例注入,所以提示我们错误。

    如下图,会有红色波浪线。

    尽管这个错误提示并不影响运行,但是看起来很不舒服,所以我们可以在对应的接口上添加 bean 的声明,如下:

    @Repository // 也可以使用@Component,效果都是一样的,只是为了声明为bean
    @Mapper
    public interface UserDao {
    	
    	@Insert("insert into user(account, password, user_name) " +
                "values(#{user.account}, #{user.password}, #{user.name})")
        int insertUser(@Param("user") User user) throws RuntimeException;
    }

    基于注解的开发也有其他手段帮助 Mybatis 找到 mapper,那就是 @MapperScan 注解,可以在启动类上添加该注解,自动扫描包路径下的所有接口。

    @SpringBootApplication
    @MapperScan("com.scut.thunderlearn.dao")
    public class UserEurekaClientApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(UserEurekaClientApplication.class, args);
        }
    }

    “spring mybatis获取mapper的方式有哪些”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注本站网站,小编将为大家输出更多高质量的实用文章!

    《spring mybatis获取mapper的方式有哪些.doc》

    下载本文的Word格式文档,以方便收藏与打印。