开发者

spring-mybatis获取mapper的四种方式汇总

目录
  • spring-myBATis获取mapper方js式汇总
    • 1.用实现类获取这个用户
    • 2.SqlSessionDaoSupport获取
    • 3.MapperFactoryBean
    • 4.MapperScannerConfigurer
  • 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");
        http://www.devze.com  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="basePackagejavascript" 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(Us开发者_Go开发erMapper.class);
          for (User user : bean.selectAllUser()) {
            System.out.prinjavascripttln(user);
          }
        }

      mybatis的mapper注解

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

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

      @Mapper
      public interface UserDao {
       ...
      }

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

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

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

      spring-mybatis获取mapper的四种方式汇总

      尽管这个错误提示并不影响运行,但是看起来很不舒服,所以我们可以在对应的接口上添加 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);
          }
      }
      

      但是感觉有些麻烦。

      总结

      以上为个人经验,希望能给大家一个参考,也希望大家多编程客栈多支持我们。

      0

      上一篇:

      下一篇:

      精彩评论

      暂无评论...
      验证码 换一张
      取 消

      最新开发

      开发排行榜