天天看點

快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)

如何快速建構一個Spring Boot的項目

  • 工具 idea
  • JDK版本 1.8
  • Spring Boot 版本 1.5.9
  • 環境搭建實作:最基礎前端可以通路到資料庫内的内容

開始

  1. IDEA 内部建立一個項目,項目類型選擇Spring Initializr,Project SDK選擇适合你目前環境的版本,這裡我選擇的是1.8(Spring Boot 2.0以上的版本,JDK選擇請選擇1.8即以上版本),建構服務選擇預設就好,點選Next
    快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)
  2. 填寫Group和Artifact(此處我使用的是預設,請根據實際情況填寫),項目類型選擇Maven項目,語言選擇Java,打包類型選擇Jar(SpringBoot内置Tomcat,web項目可以直接以Jar包的方式運作),Java 版本選擇8,Name自己填寫,Next
快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)

3. 選擇Spring Boot的版本,這裡先随便選一個,我們稍後在pom檔案中進行更改,

在下面的可以選擇相應的starter包,我們可以在此處快速選擇,也可以等到pom檔案中再手動添加。我們選擇最常用的最基本的幾個:Spring bootDevTools:實作熱部署,Lombok:使用Lombok的注釋,Spring Web,Mybatis和MySQL驅動,選擇完畢後,Next

快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)

4. 選擇項目儲存的名稱和路徑,然後Finish

快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)

5.等待項目下載下傳完成,下面的讀條全部完成後,我們就可以點開項目檢視項目的結構是否完整

快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)
  1. 打開pom.xml檔案,修改spring boot的版本為1.5.9,修改mybstis依賴的版本為1.3.1,我們使用阿裡的Druid資料庫連接配接池,添加Druid依賴,我是用的mysql為8.0,spring boot1.5.9預設的連接配接驅動是5.*的,修改驅動版本為8.0.11(在pom源碼中列出)
快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)
  1. 在spring boot maven plugin中添加如下配置,不配置fork無法進行熱部署
快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--Druid 資料庫連接配接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--使用的MySQL是8.0 使用5.*的請忽略-->
            <version>8.0.11</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>



           
  1. 開始配置項目,我們選擇使用yum檔案進行配置,在resources檔案夾下建立application.yml,删除原來的application.properties,在yum檔案中配置下面的内容,此處使用的為8.0的Mysql,8.0以下版本請修改連接配接驅動的名稱
# 配置資料庫連接配接 8.0
spring:
  datasource:
    # =====================MySQL相關配置=====================
    # 資料庫類型
    name: mysql
    #資料庫連接配接驅動
    driver-class-name: com.mysql.cj.jdbc.Driver
    #資料庫連接配接url
    url: jdbc:mysql://127.0.0.1:3306/資料庫名?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    #資料庫連接配接賬号
    username: root
    #資料庫連接配接密碼
    password: root
    #使用druid資料源
    type: com.alibaba.druid.pool.DruidDataSource
    #==================druid相關配置=========================================
    druid:
      #監控統計用的filter:stat 日志用filter:log4j 防禦sql注入用filter:wall
      filters: stat,log4j,wall
      #最大連結數量
      max-active: 20
      #初始化時建立實體連接配接的個數 初始化發生在顯示調用init() 或者第一次getConnection時
      initial-size: 1
      #擷取連接配接時的最大等待時間 毫秒
      max-wait: 60000
      #最小連接配接池數量
      min-idle: 1
      time-between-eviction-runs-millis: 60000
      #連結保持空閑而不被驅逐的最長時間
      min-evictable-idle-time-millis: 300000
      #用來檢驗連接配接是否有效的sql mysql為select 1
      # 如果validationQuery為null,testOnBorrow、testOnReturn、testWhileIdle都不會其作用
      validation-query: select 1
      # 申請連接配接的時候檢測,如果空閑時間大于timeBetweenEvictionRunsMillis,執行validationQuery檢測連接配接是否有效
      test-while-idle: true
      # 申請連接配接時執行validationQuery檢測連接配接是否有效,做了這個配置會降低性能
      test-on-borrow: false
      # 歸還連接配接時執行validationQuery檢測連接配接是否有效,做了這個配置會降低性能
      test-on-return: false
      # 歸還連接配接時執行validationQuery檢測連接配接是否有效,做了這個配置會降低性能
      pool-prepared-statements: false
      # 要啟用PSCache,必須配置大于0,當大于0時,poolPreparedStatements自動觸發修改為true
      max-open-prepared-statements: -1


# ====================mybatis==============================
mybatis:
  #配置mybatis的mapper xml檔案映射
  mapper-locations: classpath*:mapper/*.xml
  #配置pojo映射
  type-aliases-package: com.example.demo.pojo

#服務端口
server:
  port: 8080

           
  1. 建立如下包(config,controller,dao,pojo,service,mapper)
快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)
  1. 在config下建立DruidConfig

DruidConfig

package com.example.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

//标記這是一個配置類
@Configuration
public class DruidConfig {


    //配置Druid的Bean 讀取yml配置中spring.datasource為字首的配置
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }


}


           
  1. 測試表結構如下:
快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)

12.建立pojo,使用lombok的注解生成get和set方法

package com.example.demo.pojo;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

@Setter
@Getter
public class FtbAdmin implements Serializable {
    
    private Integer id;

    private String username;

    private String password;
    
}
           

13.在dao下建立mapper接口(别忘了打上mapper注解),在resources/mapper下建立xml檔案

mapper接口

package com.example.demo.dao;

import com.example.demo.pojo.FtbAdmin;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author 11699
 * @date 2020/2/15 - 13:04
 */
@Mapper
public interface FtbAdminMapper {

    public List<FtbAdmin> findAll();
}

           

mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.dao.FtbAdminMapper" >
  <resultMap id="BaseResultMap" type="com.example.demo.pojo.FtbAdmin" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>


  <select id="findAll" resultMap="BaseResultMap">
    select * from ftb_admin
  </select>


</mapper>
           

14.在service包下建立service接口,在此包下建立impl包,建立service的實作類(别忘記打上service注解)

service接口

package com.example.demo.service;

import com.example.demo.pojo.FtbAdmin;

import java.util.List;

/**
 * @author 11699
 * @date 2020/2/15 - 13:14
 *
 */
public interface FtbAdminService {

    public List<FtbAdmin> findAll();
}

           

service實作類

package com.example.demo.service.impl;

import com.example.demo.dao.FtbAdminMapper;
import com.example.demo.pojo.FtbAdmin;
import com.example.demo.service.FtbAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 11699
 * @date 2020/2/15 - 13:16
 *
 * 服務層實作,不要忘記打上service注解
 */
@Service
public class FtbAdminServiceImpl implements FtbAdminService {

    //注入mapper
    @Autowired
    private FtbAdminMapper adminMapper;

    @Override
    public List<FtbAdmin> findAll() {

        return adminMapper.findAll();
    }
}

           
  1. 在controller包下建立controller類
package com.example.demo.controller;

import com.example.demo.pojo.FtbAdmin;
import com.example.demo.service.FtbAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author 11699
 * @date 2020/2/15 - 13:29
 * 
 * @RestController:傳回整個controller傳回的都是json字元串
 * @RequestMapping("/admin"):請求映射
 */

@RestController
@RequestMapping("/admin")
public class FtbAdminController {
    
    //注入服務層
    @Autowired
    private FtbAdminService adminService;
    
    //添加映射 無需與方法名一樣
    @RequestMapping("/findAll")
    public List<FtbAdmin> findAll(){
        return adminService.findAll();
    }
}

           
  1. 在spring boot啟動類添加mapper自動掃描注解
package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//開啟mapper接口掃描,指定掃描基礎包
@MapperScan(basePackages = "com.example.demo.dao")
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

           
  1. 運作,在springboot啟動類的main方法上運作
快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)

18 啟動沒有報錯的話,我們可以開始測試了在浏覽器中輸入位址↓

http://localhost:8080/admin/findAll
           
快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)

OK,到此為止,我們就完成了!!!

附上項目的完整結構

快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)

源碼下載下傳

個人公衆号

我的個人公衆号已經開通了,正在按計劃建設中,以後的文章會第一時間釋出在公衆号中,同時也給大家準備了億點學習資料,關注公衆号背景發送:學習資料

快速建構一個Spring Boot+MyBatis的項目IDEA(附源碼下載下傳)