一. 環(huán)境搭建
hrm-parent
hrm-basic-parent //項目基本模塊
hrm-basic-utils //公共工具模塊
hrm-basic-common //公共代碼模塊
hrm-support-parent //項目支撐服務
hrm-eureka-server-1010
hrm-gateway-zuul-1020
hrm-config-server-1030
hrm-systemmanage-parent
hrm-systemmanage-common //針對系統(tǒng)管理服務公共代碼如:domain,query
hrm-systemmanage-service-2010 //針對于系統(tǒng)管理的微服務
二. 完成hrm-eureka-server-1010的搭建
三. 完成hrm-gateway-zuul-1020的搭建
四. 完成hrm-config-server-1030的搭建
五:完成hrm-systemmanage-service-2010的搭建
1. 導入依賴
2. 注冊到注冊Eureka
3. 使用代碼生成器mybatis-plus完成數(shù)據(jù)字典的CRUD
在hrm-basic-parent下創(chuàng)建一個獨立的模塊mybatis-plus
導入mybatis-plus的依賴
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 在resources下創(chuàng)建配置文件mybatiesplus-config.properties
#此處為本項目src所在路徑(代碼生成器輸出路徑),注意一定是當前項目所在的目錄喲
#mapper,servier,controller輸出目錄
OutputDir=E:/GitLocalRepository/hrm/hrm-system-parent/hrm-system-service-2010/src/main/java
#mapper.xml SQL映射文件目錄
OutputDirXml=E:/GitLocalRepository/hrm/hrm-system-parent/hrm-system-service-2010/src/main/resources
#domain,query輸出的目錄
OutputDirBase=E:/GitLocalRepository/hrm/hrm-system-parent/hrm-system-common/src/main/java
#設置作者
author=hfy
#自定義包路徑
parent=com.hanfengyi.system
#數(shù)據(jù)庫連接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///hrm-system
jdbc.user=root
jdbc.pwd=112334
- 在resources下創(chuàng)建一個templates文件夾導入query、controller的模板址芯,對模板簡單修改欺税,保證包名的正確
模板的文件名:query.java.vm controller.java.vm
controller:
package ${package.Controller};
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import cn.itsource.hrm.query.${entity}Query;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller {
@Autowired
public ${table.serviceName} ${table.entityPath}Service;
/**
* 保存和修改公用的
* @param ${table.entityPath} 傳遞的實體
* @return Ajaxresult轉換結果
*/
@RequestMapping(value="/save",method= RequestMethod.POST)
public AjaxResult save(@RequestBody ${entity} ${table.entityPath}){
try {
if(${table.entityPath}.getId()!=null){
${table.entityPath}Service.updateById(${table.entityPath});
}else{
${table.entityPath}Service.insert(${table.entityPath});
}
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setMessage("保存對象失敻俊灾螃!"+e.getMessage());
}
}
/**
* 刪除對象信息
* @param id
* @return
*/
@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
public AjaxResult delete(@PathVariable("id") Long id){
try {
${table.entityPath}Service.deleteById(id);
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setMessage("刪除對象失敗!"+e.getMessage());
}
}
//獲取用戶
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public ${entity} get(@PathVariable("id")Long id)
{
return ${table.entityPath}Service.selectById(id);
}
/**
* 查看所有的員工信息
* @return
*/
@RequestMapping(value = "/list",method = RequestMethod.GET)
public List<${entity}> list(){
return ${table.entityPath}Service.selectList(null);
}
/**
* 分頁查詢數(shù)據(jù)
*
* @param query 查詢對象
* @return PageList 分頁對象
*/
@RequestMapping(value = "/pagelist",method = RequestMethod.POST)
public PageList<${entity}> json(@RequestBody ${entity}Query query)
{
Page<${entity}> page = new Page<${entity}>(query.getPage(),query.getRows());
page = ${table.entityPath}Service.selectPage(page);
return new PageList<${entity}>(page.getTotal(),page.getRecords());
}
}
query:
package cn.itsource.hrm.query;
/**
*
* @author ${author}
* @since ${date}
*/
public class ${table.entityName}Query extends BaseQuery{
}
PageList
package com.hanfengyi.hrm.utils;
import java.util.ArrayList;
import java.util.List;
//分頁對象:easyui只需兩個屬性罪既,total(總數(shù)),datas(分頁數(shù)據(jù))就能實現(xiàn)分頁
public class PageList<T> {
private long total;
private List<T> rows = new ArrayList<>();
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
@Override
public String toString() {
return "PageList{" +
"total=" + total +
", rows=" + rows +
'}';
}
//提供有參構造方法,方便測試
public PageList(long total, List<T> rows) {
this.total = total;
this.rows = rows;
}
//除了有參構造方法搓劫,還需要提供一個無參構造方法
public PageList() {
}
}
- 創(chuàng)建啟動類用來生成代碼
package com.hanfengyi;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.*;
/**
* Created by CDHong on 2018/4/6.
*/
//代碼生成的主類
public class GenteratorCode {
//運行main方法就可以生成代碼了
public static void main(String[] args) throws InterruptedException {
//用來獲取Mybatis-Plus.properties文件的配置信息
//不要加后綴
final ResourceBundle rb = ResourceBundle.getBundle("mybatiesplus-course-config");
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(rb.getString("OutputDir"));
gc.setFileOverride(true);
gc.setActiveRecord(true);// 開啟 activeRecord 模式
gc.setEnableCache(false);// XML 二級緩存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
gc.setAuthor(rb.getString("author"));
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert());
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername(rb.getString("jdbc.user"));
dsc.setPassword(rb.getString("jdbc.pwd"));
dsc.setUrl(rb.getString("jdbc.url"));
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setTablePrefix(new String[] { "t_" });// 此處可以修改為您的表前綴
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[]{"t_course_type"}); // 需要生成的表 :
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(rb.getString("parent")); //基本包 com.hanfengyi.course
pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setEntity("domain");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 注入自定義配置睦尽,可以在 VM 中使用 cfg.abc 【可無】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
this.setMap(map);
}
};
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// 調(diào)整 controller 生成目錄演示
focList.add(new FileOutConfig("/templates/controller.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
//controller輸出完整路徑
return rb.getString("OutputDir")+ "/com/hanfengyi/course/web/controller/" + tableInfo.getEntityName() + "Controller.java";
}
});
// 調(diào)整 query 生成目錄演示
focList.add(new FileOutConfig("/templates/query.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
//query輸出完整路徑
return rb.getString("OutputDirBase")+ "/com/hanfengyi/course/query/" + tableInfo.getEntityName() + "Query.java";
}
});
// 調(diào)整 domain 生成目錄演示 笛谦, 你的domain到底要輸出到哪兒探熔?亩鬼?殖告??雳锋,你的domain怎么輸出
focList.add(new FileOutConfig("/templates/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
//domain輸出完整路徑
return rb.getString("OutputDirBase")+ "/com/hanfengyi/course/domain/" + tableInfo.getEntityName() + ".java";
}
});
// 調(diào)整 xml 生成目錄演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirXml")+ "/com/hanfengyi/course/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 自定義模板配置黄绩,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面內(nèi)容修改,
// 放置自己項目的 src/main/resources/templates 目錄下, 默認名稱一下可以不配置玷过,也可以自定義模板名稱
TemplateConfig tc = new TemplateConfig();
tc.setService("/templates/service.java.vm");
tc.setServiceImpl("/templates/serviceImpl.java.vm");
tc.setEntity(null);
tc.setMapper("/templates/mapper.java.vm");
tc.setController(null);
tc.setXml(null);
// 如上任何一個模塊如果設置 空 OR Null 將不生成該模塊爽丹。
mpg.setTemplate(tc);
// 執(zhí)行生成
mpg.execute();
}
}
BaseQuery
package com.hanfengyi.hrm.query;
/**
* 基礎查詢對象
*/
public class BaseQuery {
//關鍵字
private String keyword;
//有公共屬性-分頁
private Integer page = 1; //當前頁
private Integer rows = 10; //每頁顯示多少條
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
}
AjaxResult
package com.hanfengyi.hrm.utils;
//Ajax請求響應對象的類
public class AjaxResult {
private boolean success = true;
private String message = "操作成功!";
//返回到前臺對象
private Object resultObj;
public boolean isSuccess() {
return success;
}
public AjaxResult setSuccess(boolean success) {
this.success = success;
return this;
}
public String getMessage() {
return message;
}
public AjaxResult setMessage(String message) {
this.message = message;
return this;
}
public Object getResultObj() {
return resultObj;
}
public AjaxResult setResultObj(Object resultObj) {
this.resultObj = resultObj;
return this;
}
//AjaxResult.me()成功
//AjaxResult.me().setMessage()成功
//AjaxResult.me().setSuccess(false),setMessage("失敗");
public static AjaxResult me(){
return new AjaxResult();
}
/*
//成功
public AjaxResult() {
}
//失敗并且有提示
public AjaxResult(String message) {
this.success = false;
this.message = message;
}*/
}
- 在hrm-systemmanage-service-2010模塊中導入mybatis-plus依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.11</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
-
對報紅的代碼重新在pom中導入依賴!主配置類使用注解掃描mapper辛蚊,開啟事務管理粤蝎,使用分頁插件
@SpringBootApplication @MapperScan(value = "com.hanfengyi.system.mapper") //掃描包 @EnableTransactionManagement //開啟事務支持 public class SystemServer2010 { public static void main(String[] args) { SpringApplication.run(SystemServer2010.class ); } /** * 分頁插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
?
在resources下創(chuàng)建配置文件,集成datasource數(shù)據(jù)源袋马、mybatis-plus
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1010/eureka/ #注冊中心服務端的注冊地址
instance:
prefer-ip-address: true #使用ip進行注冊
instance-id: system-server:2010 #服務注冊到注冊中心的id
server:
port: 2010
#應用的名字
spring:
application:
name: system-server
#集成DataSource
datasource:
username: root
password: 112334
url: jdbc:mysql:///hrm-system
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#集成Mybatis-plus
mybatis-plus:
mapper-locations: classpath:com/hanfengyi/system/mapper/*Mapper.xml
- 創(chuàng)建一個單獨存放配置文件的文件夾初澎,用來從git遠程拉取配置文件,把zuul和systemmanage注冊到注冊中心虑凛!
- 簡單測試 啟動服務訪問http://localhost:2010/system/systemdictionary/list 如果能夠拿到數(shù)據(jù)碑宴,表示集成成功!
五:完成hrm-course-service-2020的搭建
與hrm-systemmanage-service-2010的搭建是一樣的
六:接口文檔Swagger的集成
①:導入依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
②:創(chuàng)建啟動類
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//對外暴露服務的包,以controller的方式暴露,所以就是controller的包.
.apis(RequestHandlerSelectors.basePackage("com.hanfengyi.system.web.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("平臺服務api")
.description("平臺服務接口文檔說明")
.contact(new Contact("test", "", "test@163.cn"))
.version("1.0")
.build();
}
}
③:測試
啟動服務桑谍,訪問:http://localhost:2010/swagger-ui.html
七:zuul網(wǎng)關整合Swagger
在zuul模塊中導入依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
創(chuàng)建兩個配置類
SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("人力資源平臺")
.description("人力資源平臺接口文檔說明")
.termsOfServiceUrl("http://localhost:1020")
.contact(new Contact("test", "", "test@163.cn"))
.version("1.0")
.build();
}
}
DocumentationConfig
resources.add(swaggerResource(服務名字延柠,服務訪問路徑,版本號);
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
@Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
resources.add(swaggerResource("系統(tǒng)管理", "/system/v2/api-docs", "2.0"));
resources.add(swaggerResource("課程管理", "/course/v2/api-docs", "2.0"));
return resources;
}
private SwaggerResource swaggerResource(String name, String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}