mac idea創(chuàng)建springboot項目集成mybatis、swagger2全過程

介紹

鑒于很多新手對mac下的idea開發(fā)工具創(chuàng)建springboot項目不太了解烁竭,今天抽了點時間,重新整理了個mac系統(tǒng)下創(chuàng)建springboot項目的詳細經(jīng)過吉挣,接下來直接進入正題派撕。

創(chuàng)建

1、打開已安裝的idea開發(fā)工具睬魂,點擊 Create new project

image

2终吼、左邊選擇Srping Initializr,然后右邊保持默認氯哮,如果jdk安裝了多個际跪,注意選擇對應(yīng)的版本,這里我的是1.8

image

3喉钢、分別填寫Group姆打、Artifact、Type肠虽、Java Version等字段,Type項選擇Maven POM是因為后面我們要采用多模塊形式開發(fā)管理,這里這個作為父工程

image

4甲献、選擇Spring Boot版本端壳,這里我選的是2.3.11,建議不要選太高版本韩玩,然后勾選所需要的依賴庫垒玲,點Next

image

5、選擇項目存放的路徑找颓,點Finish

image

6合愈、一個簡單的父工程項目結(jié)構(gòu)如圖

image

7、接下來開始創(chuàng)建子模塊叮雳,選擇頂部菜單欄中菜單 File -> New -> Module

image

8想暗、左邊依然選擇Spring Initializr,然后點Next

image

9帘不、填寫Group说莫、Artifact、Java Version等字段寞焙,Type項選擇Maven Project

image

10储狭、選擇Spring Boot 版本為2.3.11互婿,分別勾選依賴,如下圖辽狈,點擊Next

image

11慈参、點擊 Finish完成創(chuàng)建

image

集成

1、父工程中pom.xml 中添加swagger的依賴

image

2刮萌、調(diào)整manager工程的pom.xml驮配,因為我們要通過父工程來管理公共的依賴,子工程根據(jù)自己需要添加需要的依賴着茸,

<?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>com.yans.sb</groupId> <!-- 父工程的 groupId -->
        <artifactId>springboot</artifactId><!-- 父工程的 artifactId -->
        <version>0.0.1-SNAPSHOT</version><!-- 父工程的 version -->
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.yans.sb</groupId>
    <artifactId>manager</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>manager</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <!-- 這里只添加當(dāng)前子工程所需的依賴 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>

        <!--線程池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>

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

</project>

3壮锻、接下來在manager中的src目錄下創(chuàng)建對應(yīng)的文件目錄和代碼文件,結(jié)構(gòu)如圖


13.png

對應(yīng)的文件內(nèi)容如下:

  • DataSourceConfiguration
package com.yans.sb.manager.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.beans.PropertyVetoException;

/**
 * 數(shù)據(jù)庫配置類
 */
@Configuration
public class DataSourceConfiguration {

    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    @Bean(name = "dataSouce")
    public ComboPooledDataSource createDataSouce() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        //關(guān)閉連接后不自動commit
        dataSource.setAutoCommitOnClose(false);
        return dataSource;
    }
}

  • SessionFactoryConfiguration
package com.yans.sb.manager.config.dao;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * 數(shù)據(jù)庫sqlSession配置類
 */

@Configuration
public class SessionFactoryConfiguration {

    @Value("${mapper_path}")
    private String mapperPath;

    @Value("${mybatis_config_file}")
    private String mybatisConfigFilePath;

    @Autowired
    private DataSource dataSouce;
    @Value("${entity_package}")
    private String entityPackage;

    @Bean(name="sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        sqlSessionFactoryBean.setDataSource(dataSouce);
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}

  • TransactionManagementConfiguration
package com.yans.sb.manager.config.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

/**
 * 事務(wù)配置類涮阔,不可缺少猜绣,尚未知具體作用
 */
@Configuration
@EnableTransactionManagement
public class TransactionManagementConfiguration implements TransactionManagementConfigurer{

    @Autowired
    private DataSource dataSource;

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
  • Swagger2
package com.yans.sb.manager.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yans.sb.manager"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot平臺")
                .description("介紹")
                .version("4.0")
                .termsOfServiceUrl("http://localhost:18902/swagger-ui.html")
                .build();
    }
}

  • TestController
package com.yans.sb.manager.controller;


import com.yans.sb.manager.entity.TestEntity;
import com.yans.sb.manager.service.TestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Api(description = "控制層")
@RestController
@RequestMapping("/manager/test")
public class TestController {

    @Autowired
    private TestService testService;

    @ApiOperation("test方法")
    @RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
    public TestEntity test(@PathVariable Integer id) {
        System.out.println("id:" + id);
        return testService.getById(id);
    }

}
  • TestDao
package com.yans.sb.manager.dao;

import com.yans.sb.manager.entity.TestEntity;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface TestDao {

    TestEntity getById(Integer id);

}
  • TestEntity
package com.yans.sb.manager.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel("TestEntity實體類")
public class TestEntity {

    @ApiModelProperty("id 字段")
    protected Integer id;

    @ApiModelProperty("magicId 字段")
    protected String magicId;

    @ApiModelProperty("firstName 字段")
    protected String firstName;

    @ApiModelProperty("lastName 字段")
    protected String lastName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getMagicId() {
        return magicId;
    }

    public void setMagicId(String magicId) {
        this.magicId = magicId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}
  • TestService
package com.yans.sb.manager.service;


import com.yans.sb.manager.dao.TestDao;
import com.yans.sb.manager.entity.TestEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TestService {

    @Autowired
    private TestDao testDao ;

    public TestEntity getById(Integer id){
        return testDao.getById(id);
    }
}
  • TestDaoMapper.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.yans.sb.manager.dao.TestDao">
    <!-- 根據(jù)主鍵查詢-->
    <select id="getById" resultType="com.yans.sb.manager.entity.TestEntity" parameterType="java.lang.Integer" >
        select  *
        from test
        where id = #{id}
    </select>
</mapper>
  • 創(chuàng)建表的sql
CREATE TABLE `test` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `magic_id` varchar(32) NOT NULL,
  `first_name` varchar(32) NOT NULL,
  `last_name` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
  • mybatis-config.xml
<?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>
    <!--配置全局屬性-->
    <settings>
        <!--使用jdbc的getGeneratedKeys獲取數(shù)據(jù)庫自增主鍵值-->
        <setting name="useGeneratedKeys" value="true"/>
        <!--使用列標(biāo)簽替換列別名 默認未true-->
        <setting name="useColumnLabel" value="true" />
        <!--開啟駝峰式命名轉(zhuǎn)換:Table{create_time} -> Entity{createTime}-->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>
  • application.properties

#1.項目啟動的端口
server.port=18902

#2.數(shù)據(jù)庫連接參數(shù)
#2.1jdbc驅(qū)動,根據(jù)對應(yīng)類廠家敬特,這里mysql的驅(qū)動
jdbc.driver=com.mysql.cj.jdbc.Driver
#2.2數(shù)據(jù)庫連接url掰邢,包括ip(127.0.0.1)、端口(3306)伟阔、數(shù)據(jù)庫名(testdb)
jdbc.url=jdbc:mysql://127.0.0.1:3306/cp?useUnicode=true&characterEncoding=utf-8&useSSL=false
#2.3數(shù)據(jù)庫賬號名
jdbc.username=root
#2.4數(shù)據(jù)庫密碼
jdbc.password=111111

#3.Mybatis配置
#3.1 mybatis配置文件所在路徑
mybatis_config_file=mybatis-config.xml
#3.2 mapper文件所在路徑辣之,這樣寫可匹配mapper目錄下的所有mapper,包括其子目錄下的
mapper_path=/mapper/**/**.xml
#3.3 entity所在包
entity_package=com.yans.sb.manager.entity

測試

1皱炉、啟動好數(shù)據(jù)庫召烂,創(chuàng)建目標(biāo)數(shù)據(jù)庫,創(chuàng)建表

14.png
15.png

2娃承、啟動項目奏夫,點擊這個三角形的圖標(biāo)


16.png

3、打開postman工具历筝,配置如下酗昼,可以看到數(shù)據(jù)已經(jīng)成功返回


postman.png

至此,項目工程搭建完畢梳猪,項目實例工程已經(jīng)放到github麻削,需要的自取,地址:https://github.com/andyccc/springbootdemo.git

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末春弥,一起剝皮案震驚了整個濱河市呛哟,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌匿沛,老刑警劉巖扫责,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異逃呼,居然都是意外死亡鳖孤,警方通過查閱死者的電腦和手機者娱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來苏揣,“玉大人黄鳍,你說我怎么就攤上這事∑叫伲” “怎么了框沟?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長增炭。 經(jīng)常有香客問我街望,道長,這世上最難降的妖魔是什么弟跑? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮防症,結(jié)果婚禮上孟辑,老公的妹妹穿的比我還像新娘。我一直安慰自己蔫敲,他們只是感情好饲嗽,可當(dāng)我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著奈嘿,像睡著了一般貌虾。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上裙犹,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天尽狠,我揣著相機與錄音,去河邊找鬼叶圃。 笑死袄膏,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的掺冠。 我是一名探鬼主播沉馆,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼德崭!你這毒婦竟也來了斥黑?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤眉厨,失蹤者是張志新(化名)和其女友劉穎锌奴,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體憾股,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡缨叫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年椭符,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片耻姥。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡销钝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出琐簇,到底是詐尸還是另有隱情蒸健,我是刑警寧澤,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布婉商,位于F島的核電站似忧,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏丈秩。R本人自食惡果不足惜盯捌,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蘑秽。 院中可真熱鬧饺著,春花似錦、人聲如沸肠牲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽缀雳。三九已至渡嚣,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間肥印,已是汗流浹背识椰。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留深碱,地道東北人裤唠。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像莹痢,于是被迫代替她去往敵國和親种蘸。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,573評論 2 359

推薦閱讀更多精彩內(nèi)容