Spring整合Mybatis Java代码配置

Spring整合Mybatis-Maven


一、导入依赖以及一些配置

  • 注意Spring整合Mybatis需要引入Mybatis-Spring的依赖
<!-- 统一JDK版本 -->
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>11</maven.compiler.source>
  <maven.compiler.target>11</maven.compiler.target>
</properties>

<dependencies>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
  <!-- spring MVC-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.7</version>
  </dependency>
  <!--    junit 单元测试-->
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.7.0</version>
    <scope>test</scope>
  </dependency>

  <!--AOP织入-->
  <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
  </dependency>

  <!--导入mybatis依赖-->
  <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
  </dependency>

  <!--导入mysql数据库依赖-->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
  </dependency>

  <!--Spring整合Mybatis,所需要的适配器依赖-->
  <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.6</version>
  </dependency>

  <!-- Spring Jdbc-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.6</version>
  </dependency>

</dependencies>

<!-- 资源文件加载问题 -->
<build>
  <resources>
    <resource>
      <directory>
        src/main/resources
      </directory>
      <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
    </resource>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
      <filtering>true</filtering>
    </resource>
  </resources>
</build>

二、Spring整合Mybatis

  1. Mybatis配置文件-配置交给Spring做,Mybatis只需要声明Mapper

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
      <mappers>
        <mapper class="com.aguo.dao.TestMapper" />
      </mappers>
    </configuration>
    
  2. 使用Java源代码做Spring整合Mybatis的配置文件

    1. 导入数据源,这里选择Mybatis原生数据源以及Druid数据源

      • Mybatis原生数据源

        /**
         * mybaits原生数据源
         * @return
         */
        @Bean
        public PooledDataSource jdbcDataSource(){
          PooledDataSource dataSource = new PooledDataSource();
          dataSource.setDriver("com.mysql.cj.jdbc.Driver");
          dataSource.setUrl("jdbc:mysql:///user?serverTimezone=UTC");
          dataSource.setUsername("root");
          dataSource.setPassword("123456");
          return dataSource;
        }
        
      • Druid数据连接池数据源

        /**
         * Druid连接池数据源
         * @return
         */
        @Bean
        public DruidDataSource druidDataSource(){
          DruidDataSource dataSource = new DruidDataSource();
          dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
          dataSource.setUrl("jdbc:mysql:///user?serverTimezone=UTC");
          dataSource.setUsername("root");
          dataSource.setPassword("123456");
          return dataSource;
        }
        
    2. 注入SqlSessionFactory到Spring容器中

      /**
       * 配置SqlSessionFactory
       * @return
       * @throws Exception
       */
      @Bean
      public SqlSessionFactory sqlSessionFactory() throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        factoryBean.setDataSource(druidDataSource());
        return factoryBean.getObject();
      }
      
    3. 注入SqlSession到Spring容器中

      /**
       * 配置SqlSession对象
       * @return
       */
      @Bean
      public SqlSession sqlSession(){
        try {
          return sqlSessionFactory().openSession();
        } catch (Exception e) {
          e.printStackTrace();
        }
        return null;
      }
      
    4. Spring整合Mybatis的完整Java配置文件

      package com.aguo.config;
      
      import com.aguo.dao.TestMapper;
      import com.alibaba.druid.pool.DruidDataSource;
      import org.apache.ibatis.datasource.pooled.PooledDataSource;
      import org.apache.ibatis.session.SqlSession;
      import org.apache.ibatis.session.SqlSessionFactory;
      import org.mybatis.spring.SqlSessionFactoryBean;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.ComponentScan;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.core.io.ClassPathResource;
      
      /**
       * @Author Code Fruit
       * @Email 1260839205@qq.com
       * @Date 2021/6/20 下午4:05
       */
      
      @ComponentScan
      @Configuration
      public class MybatisConfig {
      
          /**
           * mybaits原生数据源
           * @return
           */
          @Bean
          public PooledDataSource jdbcDataSource(){
              PooledDataSource dataSource = new PooledDataSource();
              dataSource.setDriver("com.mysql.cj.jdbc.Driver");
              dataSource.setUrl("jdbc:mysql:///user?serverTimezone=UTC");
              dataSource.setUsername("root");
              dataSource.setPassword("123456");
              return dataSource;
          }
      
          /**
           * Druid连接池数据源
           * @return
           */
          @Bean
          public DruidDataSource druidDataSource(){
              DruidDataSource dataSource = new DruidDataSource();
              dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
              dataSource.setUrl("jdbc:mysql:///user?serverTimezone=UTC");
              dataSource.setUsername("root");
              dataSource.setPassword("123456");
              return dataSource;
          }
      
          /**
           * 配置SqlSessionFactory
           * @return
           * @throws Exception
           */
          @Bean
          public SqlSessionFactory sqlSessionFactory() throws Exception{
              SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
              factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
              factoryBean.setDataSource(druidDataSource());
              return factoryBean.getObject();
          }
      
          /**
           * 配置SqlSession对象
           * @return
           */
          @Bean
          public SqlSession sqlSession(){
              try {
                  return sqlSessionFactory().openSession();
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return null;
          }
      }
      
      
  3. 编写Admin类

    package com.aguo.domain;
    
    import org.springframework.stereotype.Component;
    
    /**
     * @Author Code Fruit
     * @Email 1260839205@qq.com
     * @Date 2021/6/6 上午10:52
     */
    @Component(value = "adminUser")
    public class AdminUser {
    
        private int id;
        private String username;
        private String password;
    
        public AdminUser() {
        }
    
        public AdminUser(int id, String username, String password) {
            this.id = id;
            this.username = username;
            this.password = password;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        @Override
        public String toString() {
            return "AdminUser{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }
    }
    
    
  4. 编写TestMapper接口,查询用户数据

    package com.aguo.dao;
    
    import com.aguo.domain.AdminUser;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    /**
     * @Author Code Fruit
     * @Email 1260839205@qq.com
     * @Date 2021/6/20 下午4:39
     */
    
    public interface TestMapper {
    
        @Select("select * from adminuser where id = #{id}")
        AdminUser getAdminById(@Param("id") int id);
    }
    
    
  5. 测试类

    package com.aguo.test;
    
    import com.aguo.dao.TestMapper;
    import com.aguo.domain.AdminUser;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.jupiter.api.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    /**
     * @Author Code Fruit
     * @Email 1260839205@qq.com
     * @Date 2021/6/20 下午4:42
     */
    public class Spring_Mybatis_Test {
    
        @Test
        public void myTest(){
            ApplicationContext context = new AnnotationConfigApplicationContext(com.aguo.config.MybatisConfig.class);
            SqlSession sqlSession = context.getBean("sqlSession", SqlSession.class);
            TestMapper mapper = sqlSession.getMapper(TestMapper.class);
            AdminUser adminById = mapper.getAdminById(1);
            System.out.println(adminById);
            sqlSession.close();
        }
    }
    
    
  6. 注意事项

    1. 注入SqlSessionFactory到容器中的时候,需要读取Mybatis的配置文件(在Mabatis-Spring官方文档中没有提到,所以我踩坑了)

      读取配置文件的方式

      factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
      

      不写这句话会报错:

      org.apache.ibatis.binding.BindingException: Type interface com.aguo.dao.TestMapper is not known to the MapperRegistry.
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值