第一步 新建springboot項(xiàng)目
通過idea新建項(xiàng)目,選擇Spring Initializr,其他可以默認(rèn),點(diǎn)擊Next即可。

New Project
如下圖自定義 Group 和 Artifact、選好項(xiàng)目類型,通常使用Maven Project,語言java,打包方式,springboot我選擇使用 jar 包方式。

New Project
選擇幾個常用的依賴,后期可根據(jù)需要自行添加。

New Project
選擇項(xiàng)目存儲位置。

New Project
第二步 添加基本配置文件
配置數(shù)據(jù)源、mybatis 和 druid
1、在pom.xml中添加以下依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
2、在application.properties中添加數(shù)據(jù)源及 druid配置如下:
server.port=8080
spring.datasource.url=jdbc:mysql://( 填寫數(shù)據(jù)庫所在的主機(jī)IP ):3306/( 填寫數(shù)據(jù)庫名稱 )
spring.datasource.username=username(填寫數(shù)據(jù)庫用戶名)
spring.datasource.password=password(填寫密碼)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#druid配置
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
#配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計(jì),'wall'用于防火墻
spring.datasource.filters=stat,wall,logback
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.useGlobalDataSourceStat=true
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#spring.datasource.schema=sql文件路徑,可以直接建表
#mybatis 配置
mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:com/example/demo/**/*Mapper.xml
也可以是yml格式的:
server:
port: 8080
spring:
datasource:
username: username
password: password
url: jdbc:mysql://( 填寫你的數(shù)據(jù)庫所在主機(jī)ip ):3306/( 填寫數(shù)據(jù)名稱 )
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 數(shù)據(jù)源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計(jì),'wall'用于防火墻
filters: stat,wall,logback
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# schema:
# - classpath:sql/user.sql
# mybatis 配置
mybatis:
config-location: classpath:mybatis-config.xml
mapper-locations: classpath:com/example/demo/**/*Mapper.xml
3、在 resources 文件夾下新建 mybatis-config.xml,內(nèi)容如下:
<?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>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="false"/>
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="REUSE"/>
<setting name="defaultStatementTimeout" value="25000"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="callSettersOnNulls" value="true"/>
</settings>
</configuration>
4、在 pom.xml 中添加 mybatis.generator 插件,可以根據(jù)generatorConfig.xml配置文件生成 mybatis 映射、model層、dao層和 mapper層。
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
generatorConfig.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 配置mysql 驅(qū)動jar包路徑.用了絕對路徑 -->
<classPathEntry location="C:\Users\JingXi\.m2\repository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar"/>
<context id="wangyongzhi_mysql_tables" targetRuntime="MyBatis3">
<!-- 防止生成的代碼中有很多注釋,加入下面的配置控制 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
<!-- 數(shù)據(jù)庫連接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.31.128:3306/copyrightblock?useUnicode=true;characterEncoding=UTF-8"
userId="copyrightblock"
password="123456">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 數(shù)據(jù)表對應(yīng)的model層 -->
<javaModelGenerator targetPackage="com.example.demo.model" targetProject="src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- sql mapper 映射配置文件 -->
<sqlMapGenerator targetPackage="com.example.demo.mapper" targetProject="src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- mybatis3中的mapper接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.dao" targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 數(shù)據(jù)表進(jìn)行生成操作 schema:相當(dāng)于庫名; tableName:表名; domainObjectName:對應(yīng)的DO -->
<table schema="test" tableName="test_user" domainObjectName="TestUser"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
注意classPathEntry location的路徑,配置好后可以運(yùn)行插件即可生成三層結(jié)構(gòu),之后自行追加 service和 serviceimp。
注意:要在主類DemoApplication中添加注解@MapperScan掃描到 dao層接口。
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.example.demo.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
出現(xiàn) target中沒有 mapper.xml解決辦法,在pom.xml中的 built 中插入下面配置
<resources>
<!-- mapper.xml文件在java目錄下 -->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
druid的管理界面,需要添加一個 DruidConfig.java類:
package com.example.demo.common.druidconfig;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Author: Jankin
* Date:2019/2/21
* Description:
*/
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的監(jiān)控
//1、配置一個管理后臺的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默認(rèn)就是允許所有訪問
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一個web監(jiān)控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
啟動項(xiàng)目后訪問http://localhost:8080/druid/# 可以進(jìn)入以下界面:

New Project
輸入配置的賬號密碼后進(jìn)入界面

New Project
第三步 可以寫代碼了
補(bǔ)充建表sql文件,在運(yùn)行mybatis.generator插件之前先把表建好
CREATE TABLE ttai_user (
id BIGINT NOT NULL auto_increment COMMENT '主鍵id',
user_account VARCHAR(20) NOT NULL COMMENT '用戶賬號',
user_pwd VARCHAR(50) NOT NULL COMMENT '賬號id表,新注冊用戶的record_id',
user_nickname VARCHAR(50) NOT NULL COMMENT '用戶',
user_email VARCHAR(320) NOT NULL COMMENT '用戶郵箱地址',
del_sign INT NOT NULL DEFAULT 0 COMMENT '0:未刪除 1:已刪除',
create_tx_stamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時間',
lastup_tx_stamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間',
PRIMARY KEY ( id )
);
寫了個小接口:
package com.example.demo.controller;
import com.example.demo.common.Result;
import com.example.demo.model.TtaiUser;
import com.example.demo.service.TtaiUserService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Author: Jankin
* Date:2019/2/21
* Description:
*/
@RestController
public class TestContrller {
private final TtaiUserService ttaiUserService;
@Autowired
public TestContrller(TtaiUserService ttaiUserService) {
this.ttaiUserService = ttaiUserService;
}
@PostMapping("/test")
public String add(@RequestParam("account") String account,
@RequestParam("pwd") String pwd){
TtaiUser user = new TtaiUser();
user.setUserAccount(account);
user.setUserPwd(pwd);
user.setUserNickname("null");
user.setUserEmail("null");
this.ttaiUserService.insertSelective(user);
return new Gson().toJson(new Result());
}
}
成功運(yùn)行

New Project
發(fā)起一個post請求看看效果:

New Project

New Project
不小心點(diǎn)了兩次沒有做用戶名唯一性校驗(yàn),所以插入了兩條一樣的數(shù)據(jù)。
原文鏈接https://zzjing.top/2019/02/21/springboot%E9%A1%B9%E7%9B%AE%E6%90%AD%E5%BB%BA/
這是項(xiàng)目地址https://github.com/jingxizhu/springbootbuild
下回分享使用通用mapper~