1. 程式人生 > 其它 >springboot接入mybatis管理資料庫

springboot接入mybatis管理資料庫

springboot接入mybatis管理資料庫

  • 1.建立springboot專案(使用開發工具類似IDEA新建Springboot專案)

  • 2.pom依賴引入

      <!-- mysql-connector-java -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${mysql.version}</version>
      </dependency>
      <!-- mybatis-spring-boot-starter -->
      <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>${mybatis.version}</version>
      </dependency>
    
  • 3.配置檔案(application.yml)

      # 資料庫配置
      spring:
        datasource:
          # 驅動
          driver-class-name: com.mysql.cj.jdbc.Driver
          # url
          url: jdbc:mysql://xxx:3306/second_kill?characterEncoding=utf-8&useSSL=false
          # 使用者名稱
          username: xxx
          # 密碼
          password: xxx
          dbcp2:
            # 驗證查詢
            validation-query: select 1 from dual
      
      # MyBatis
      mybatis:
        # 包別名配置
        type-aliases-package: com.kinson.springboot.domain
        # mapper xml位置配置
        mapper-locations: classpath:/secondKill/*.xml
        # 控制檯列印sql(https://www.cnblogs.com/kingsonfu/p/9245731.html)
        configuration:
          log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
  • 4.啟動類加MapperScan註解

      @SpringBootApplication
      // 多個以逗號分隔
      @MapperScan({"com.kinson.springboot.mapper", "xxx"})
      public class SecondKillProSpringboot {
      
          public static void main(String[] args) {
              SpringApplication.run(SecondKillProSpringboot.class, args);
          }
      }
    
  • 5.新加資料庫表對映類

      public class User {
      
          private Integer id;
      
          private String userName;
      
          public Integer getId() {
              return id;
          }
      
          public void setId(Integer id) {
              this.id = id;
          }
      
          public String getUserName() {
              return userName;
          }
      
          public void setUserName(String userName) {
              this.userName = userName;
          }
      }
    
  • 6.新增對應的Mapper類

    public interface UserMapper {

      /**
       * 查詢所有使用者
       *
       * @return
       */
      List<User> selectUserList();
    

    }

  • 7.新增對應Mapper的對映xml檔案

      <select id="selectUserList" parameterType="User" resultMap="UserResult">
          select * from user
      </select>
    
  • 8.之後就可以使用mapper在service注入使用了

Github原始碼springboot-mybatis