先从Idea上新建项目,过程选项一直下一步就可以了,路径名等请自定义。
规范的项目路径便于问题的定位及项目的维护
在application.yml中添加数据源配置和mybatis的mapper.xml的路径配置。
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
mybatis:
mapper-locations:
- classpath:mapper/*.xml
- classpath*:com/**/mapper/*.xml
为了引入mybatis及mbg等相关组件,需要添加以下依赖:mybatis、mybatis-generator、druid、mysql-connector-java。
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.7version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.15version>
dependency>
配置数据库连接,Mybatis生成器生成模型,mapper接口及mapper.xml路径。
<generatorConfiguration>
<properties resource="generator.properties"/>
<context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<property name="javaFileEncoding" value="UTF-8"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
<commentGenerator type="com.hzf.mymall.mgb.CommentGenerator">
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
<property name="addRemarkComments" value="true"/>
commentGenerator>
<jdbcConnection driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.userId}"
password="${jdbc.password}">
<property name="nullCatalogMeansCurrent" value="true" />
jdbcConnection>
<javaModelGenerator targetPackage="com.hzf.mymall.model" targetProject="src\main\java"/>
<sqlMapGenerator targetPackage="com.hzf.mymall.mapper" targetProject="src\main\resources"/>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.hzf.mymall.mapper"
targetProject="src\main\java"/>
<table tableName="%">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
table>
context>
generatorConfiguration>
用于配置需要动态生成的mapper接口的路径
package com.hzf.mymall.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
/**
* @author:010980380
* @date:2020-10-26
* @verison:1.0.0
* @description:MyBatis配置类
*/
@Configuration
@MapperScan({"com.hzf.mymall.mapper","com.hzf.mymall.dao"})
public class MyBatisConfig {
}
package com.hzf.mymall.mgb;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.Properties;
/**
* @author:010980380
* @date:2020-10-26
* @verison:1.0.0
* @description:
*/
public class CommentGenerator extends DefaultCommentGenerator {
private boolean addRemarkComments = false;
private static final String EXAMPLE_SUFFIX="Example";
private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";
/**
* 设置用户配置的参数
*/
@Override
public void addConfigurationProperties(Properties properties) {
super.addConfigurationProperties(properties);
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
}
/**
* 给字段添加注释
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
//根据参数和备注信息判断是否添加备注信息
if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
// addFieldJavaDoc(field, remarks);
//数据库中特殊字符需要转义
if(remarks.contains("\"")){
remarks = remarks.replace("\"","'");
}
//给model的字段添加swagger注解
field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
}
}
/**
* 给model的字段添加注释
*/
private void addFieldJavaDoc(Field field, String remarks) {
//文档注释开始
field.addJavaDocLine("/**");
//获取数据库字段的备注信息
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
for(String remarkLine:remarkLines){
field.addJavaDocLine(" * "+remarkLine);
}
addJavadocTag(field, false);
field.addJavaDocLine(" */");
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
super.addJavaFileComment(compilationUnit);
//只在model中添加swagger注解类的导入
if(!compilationUnit.isJavaInterface()&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
}
}
}
package com.hzf.mymall.mgb;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author:010980380
* @date:2020-10-21
* @verison:1.0.0
* @description:用于生成MBG的代码
*/
public class Generator {
public static void main(String[] args) throws Exception {
//MBG 执行过程中的警告信息
List<String> warnings = new ArrayList<String>();
//当生成的代码重复时,覆盖原代码
boolean overwrite = true;
//读取我们的 MBG 配置文件
InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close();
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
//创建 MBG
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
//执行生成代码
myBatisGenerator.generate(null);
//输出警告信息
for (String warning : warnings) {
System.out.println(warning);
}
}
}
基础的通用类包括:自定义操作码的接口、常用操作码的枚举,分页数据的封装类,通用的返回对象。
package com.hzf.mymall.common;
/**
* @author:010980380
* @date:2020-10-26
* @verison:1.0.0
* @description:通用返回对象
*/
public class CommonResult<T> {
private long code;
private String message;
private T data;
protected CommonResult(){}
protected CommonResult(long code,String message,T data){
this.code = code;
this.message = message;
this.data = data;
}
/**
* 成功返回结果
* @param data 获取的数据
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 15:43
*/
public static <T> CommonResult<T> success(T data){
return new CommonResult<T>(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMessage(),data);
}
/**
* 成功返回结果
* @param data 获取的数据
* @param message 提示信息
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 15:43
*/
public static <T> CommonResult<T> success(T data,String message){
return new CommonResult<T>(ResultCode.SUCCESS.getCode(),message,data);
}
/**
* 失败返回结果
* @param errorCode 错误码对象
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 15:49
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode){
return new CommonResult<T>(errorCode.getCode(),errorCode.getMessage(),null);
}
/**
* 失败返回结果
* @param errorCode 错误码对象
* @param message 提示信息
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 15:50
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode,String message){
return new CommonResult<T>(errorCode.getCode(),message,null);
}
/**
* 失败返回结果
* @param message 提示信息
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 15:50
*/
public static <T> CommonResult<T> failed(String message){
return new CommonResult<T>(ResultCode.FAILED.getCode(),message,null);
}
/**
* 失败返回结果
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 15:51
*/
public static <T> CommonResult<T> failed(){
return failed(ResultCode.FAILED);
}
/**
* 参数验证失败返回结果
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 16:04
*/
public static <T> CommonResult<T> vaildateFailed(){
return failed(ResultCode.VALIDATE_FAILED);
}
/**
* 参数验证失败返回结果
* @param message 提示信息
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 16:05
*/
public static <T> CommonResult<T> validateFailed(String message){
return failed(ResultCode.VALIDATE_FAILED,message);
}
/**
* 未登录返回结果
* @param data
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 16:04
*/
public static <T> CommonResult<T> unauthorized(T data){
return new CommonResult<T>(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage(),data);
}
/**
* 未授权返回结果
* @param data
* @return CommonResult
* @author huangzifan
* @since 2020-10-26 16:04
*/
public static <T> CommonResult<T> forbidden(T data){
return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(),ResultCode.FORBIDDEN.getMessage(),data);
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
package com.hzf.mymall.common;
import com.github.pagehelper.PageInfo;
import java.util.List;
/**
* @author:010980380
* @date:2020-10-26
* @verison:1.0.0
* @description:分页数据的封装类
*/
public class CommonPage<T> {
private Integer pageNum;
private Integer pageSize;
private Integer totalpage;
private Long total;
private List<T> list;
public static <T> CommonPage<T> restPage(List<T> list){
CommonPage result =new CommonPage<T>();
PageInfo<T> pageInfo = new PageInfo<T>(list);
result.setPageNum(pageInfo.getPageNum());
result.setPageSize(pageInfo.getPageSize());
result.setTotalpage(pageInfo.getPages());
result.setTotal(pageInfo.getTotal());
result.setList(pageInfo.getList());
return result;
}
public static <T> CommonPage<T> restPage(PageInfo<T> pageInfo){
CommonPage result = new CommonPage<T>();
result.setPageNum(pageInfo.getPageNum());
result.setPageSize(pageInfo.getPageSize());
result.setTotalpage(pageInfo.getPages());
result.setTotal(pageInfo.getTotal());
result.setList(pageInfo.getList());
return result;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalpage() {
return totalpage;
}
public void setTotalpage(Integer totalpage) {
this.totalpage = totalpage;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
package com.hzf.mymall.common;
/**
* @author:010980380
* @date:2020-10-26
* @verison:1.0.0
* @description:自定义错误码接口
*/
public interface IErrorCode {
long getCode();
String getMessage();
}
package com.hzf.mymall.common;
/**
* @author:010980380
* @date:2020-10-26
* @verison:1.0.0
* @description:枚举常用的操作码
*/
public enum ResultCode implements IErrorCode{
SUCCESS(200,"操作成功"),
FAILED(500,"操作失败"),
VALIDATE_FAILED(404,"参数检验失败"),
UNAUTHORIZED(401,"暂未登陆或token已经过期"),
FORBIDDEN(403,"没有相关权限");
private long code;
private String message;
ResultCode(long code, String message) {
this.code = code;
this.message = message;
}
@Override
public long getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
package com.hzf.mymall.service;
import com.hzf.mymall.model.PmsBrand;
import java.util.List;
/**
* @author:010980380
* @date:2020-10-26
* @verison:1.0.0
* @description:PmsBrand Service接口
*/
public interface PmsBrandService {
List<PmsBrand> listAllBrand();
int createBrand(PmsBrand brand);
int updateBrand(Long id,PmsBrand brand);
int deleteBrand(Long id);
List<PmsBrand> listBrand(int pageNum,int pageSize);
PmsBrand getBrand(Long id);
}
package com.hzf.mymall.service.impl;
import com.github.pagehelper.PageHelper;
import com.hzf.mymall.mapper.PmsBrandMapper;
import com.hzf.mymall.model.PmsBrand;
import com.hzf.mymall.model.PmsBrandExample;
import com.hzf.mymall.service.PmsBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @author:010980380
* @date:2020-10-26
* @verison:1.0.0
* @description:PmsBrand 实现类
*/
public class PmsBrandServiceImpl implements PmsBrandService {
@Autowired
private PmsBrandMapper brandMapper;
@Override
public List<PmsBrand> listAllBrand() {
return brandMapper.selectByExample(new PmsBrandExample());
}
@Override
public int createBrand(PmsBrand brand) {
return brandMapper.insertSelective(brand);
}
@Override
public int updateBrand(Long id,PmsBrand brand) {
brand.setId(id);
return brandMapper.updateByPrimaryKeySelective(brand);
}
@Override
public int deleteBrand(Long id) {
return brandMapper.deleteByPrimaryKey(id);
}
@Override
public List<PmsBrand> listBrand(int pageNum, int pageSize) {
PageHelper.startPage(pageNum,pageSize);
return brandMapper.selectByExample(new PmsBrandExample());
}
@Override
public PmsBrand getBrand(Long id) {
return brandMapper.selectByPrimaryKey(id);
}
}
package com.hzf.mymall.controller;
import com.hzf.mymall.common.CommonPage;
import com.hzf.mymall.common.CommonResult;
import com.hzf.mymall.model.PmsBrand;
import com.hzf.mymall.service.PmsBrandService;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.xml.ws.RequestWrapper;
import java.util.List;
/**
* @author:010980380
* @date:2020-10-26
* @verison:1.0.0
* @description:品牌管理 Controller
*/
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
@Autowired
private PmsBrandService demoService;
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsBrand>> getBrandList(){
return CommonResult.success(demoService.listAllBrand());
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize){
List<PmsBrand> brandList = demoService.listBrand(pageNum,pageSize);
return CommonResult.success(CommonPage.restPage(brandList));
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsBrand> Brand(@PathVariable("id") Long id){
return CommonResult.success(demoService.getBrand(id));
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult createBrand(@RequestBody PmsBrand pmsBrand){
CommonResult commonResult;
int count = demoService.createBrand(pmsBrand);
if(count == 1){
commonResult = CommonResult.success(pmsBrand);
LOGGER.debug("create Brand success:{}",pmsBrand);
}else {
commonResult = CommonResult.failed("操作失败");
LOGGER.debug("createBrand failed:{}",pmsBrand);
}
return commonResult;
}
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand pmsBrandDto, BindingResult result){
CommonResult commonResult;
int count = demoService.updateBrand(id,pmsBrandDto);
if(count == 1){
commonResult = CommonResult.success(pmsBrandDto);
LOGGER.debug("updateBrand success:{}",pmsBrandDto);
}else {
commonResult = CommonResult.failed("操作失败");
LOGGER.debug("updateBrand failed:{}",pmsBrandDto);
}
return commonResult;
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult deleteBrand(@PathVariable("id") Long id){
int count = demoService.deleteBrand(id);
if(count == 1){
LOGGER.debug("deleteBrand success:{}",id);
return CommonResult.success(null);
}else{
LOGGER.debug("deleteBrand failed:{}",id);
return CommonResult.failed("操作失败");
}
}
}