SpringMVC+MyBatis Plus+Mysql+Maven

SpringMVC+MyBatis Plus+Mysql+Maven

一,目录结构

SpringMVC+MyBatis Plus+Mysql+Maven_第1张图片

二,mybatis-config.xml 文件




    
        
        
        
        
        
        
        
        
    


三,spring.xml文件




    
    

    
    

    

四,spring-mvc.xml



    
    
    
     
    
    
    
    
        
            
            
            
                
                    
                        
                        text/html;charset=UTF-8
                        application/json;charset=UTF-8
                    
                
                
                    
                        
                        DisableCircularReferenceDetect
                        
                        WriteMapNullValue
                        
                        WriteNullNumberAsZero
                        
                        WriteNullStringAsEmpty
                        
                        WriteNullListAsEmpty
                        
                        WriteNullBooleanAsFalse
                    
                
            
        
    
    
    
    
    
    
        
        
    

五,spring-mybatis.xml文件




    
    
        
        
        

        
        
        
        
        
        
        
        
        
        

        
        
        
        

        
        
        
        

        
        
        
        
        
        

        
        
    

    
    
        
        
        
        
        
        
            
                
                
                
            
        
	    
	    
	
	
	    
	    
        
            
        
	

    
    
        
    

    
    
        
    

    
    
        
            
            
            
            
            
            
            
            
            
            

            
            
            
            
            

            
        
    

    

六,config.properties

validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8&tinyInt1isBit=false&allowMultiQueries=true
jdbc_username=root
jdbc_password=root

七,log4.properties文件

log4j.rootLogger=DEBUG,CONSOLE,A
log4j.addivity.org.apache=false
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} -%-4r [%t] %-5p  %x - %m%n
log4j.appender.CONSOLE.Target=System.out
#log4j.appender.CONSOLE.charset=utf-8
log4j.appender.CONSOLE.encoding=utf-8
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.A=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A.File=${catalina.home}/logs/yo_log/PurePro_
log4j.appender.A.DatePattern=yyyy-MM-dd'.log'
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=[FH_sys]  %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L \: %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

八,myController.java.vm 代码生成器模板文件

package ${package.Controller};
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ${package.Service}.${table.serviceName};
import com.hao.common.controller.BaseController;
import com.hao.common.result.JsonResult;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import ${package.Entity}.${table.entityName};
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

#if(${restControllerStyle})
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end

/**
 * 

* $!{table.comment} 前端控制器 *

* * @author ${author} * @since ${date} */ #if(${restControllerStyle}) @RestController #else @Controller #end @RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end") #if(${kotlin}) class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end #else #if(${superControllerClass}) public class ${table.controllerName} extends ${superControllerClass} { #else public class ${table.controllerName} extends BaseController{ #end @Autowired public ${table.serviceName} i${entity}Service; /** * 初始化分页 * @param page * @param size */ @RequestMapping(value = "/init${entity}PageList", method = RequestMethod.GET) @ResponseBody public JsonResult init${entity}PageList(String page, String size){ if(page == null || size == null){ return this.renderError("${entity}传参对象为空"); }else{ Page<${entity}> pages = i${entity}Service.selectPage( new Page<>(Integer.valueOf(page), Integer.valueOf(size)), new EntityWrapper<${entity}>().orderBy("createTime",false) ); Map map = new HashMap<>(2); map.put("total", pages.getTotal()); map.put("list", pages.getRecords()); return this.renderSuccess(map); } } /** * 新增 * @param model * @return */ @RequestMapping(value = "/add${entity}", method = RequestMethod.POST) @ResponseBody public JsonResult add${entity}(@RequestBody ${entity} model){ if(model == null){ return this.renderError("${entity}传参对象为空值"); } else { if(i${entity}Service.insert(model)){ return this.renderSuccess("新增成功"); } else { return this.renderError("新增失败"); } } } /** * 更新 * @param model * @return */ @RequestMapping(value = "/update${entity}", method = RequestMethod.POST) @ResponseBody public JsonResult update${entity}(@RequestBody ${entity} model){ if (model == null){ return this.renderError("${entity}传参对象为空值"); }else { if (i${entity}Service.updateAllColumnById(model)){ return this.renderSuccess("更新成功"); }else { return this.renderError("更新失败"); } } } /** * 删除 * @param ids * @return */ @RequestMapping(value = "delete${entity}", method = RequestMethod.GET) @ResponseBody public JsonResult delete${entity}(String ids){ if(ids == null) { return this.renderError("传参对象为空值"); } else { List idList = Arrays.asList(ids.split(",")); if(i${entity}Service.deleteBatchIds(idList)){ return this.renderSuccess("删除成功"); } else { return this.renderError("删除失败"); } } } } #end

九,BaseController.java

package com.hao.common.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hao.common.result.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class BaseController {
	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;
	
	public static String LOG_ADD="新增";
	public static String LOG_UPDATE="修改";
	public static String LOG_DELETE="删除";

    /**
     * 渲染失败数据
     *
     * @return result
     */
    protected JsonResult renderError() {
        JsonResult result = new JsonResult();
        result.setSuccess(false);
        result.setStatus("500");
        return result;
    }

    /**
     * 渲染失败数据(带消息)
     *
     * @param msg 需要返回的消息
     * @return result
     */
    protected JsonResult renderError(String msg) {
        JsonResult result = renderError();
        result.setMsg(msg);
        return result;
    }

    /**
     * 渲染成功数据
     *
     * @return result
     */
    protected JsonResult renderSuccess() {
        JsonResult result = new JsonResult();
        result.setSuccess(true);
        result.setStatus("200");
        return result;
    }

    /**
     * 渲染成功数据(带信息)
     *
     * @param msg 需要返回的信息
     * @return result
     */
    protected JsonResult renderSuccess(String msg) {
        JsonResult result = renderSuccess();
        result.setMsg(msg);
        return result;
    }

    /**
     * 渲染成功数据(带数据)
     *
     * @param obj 需要返回的对象
     * @return result
     */
    protected JsonResult renderSuccess(Object obj) {
        JsonResult result = renderSuccess();
        result.setObj(obj);
        return result;
    }
    
    protected String renderJson(Object obj) throws JsonProcessingException {
        Map map  = new HashMap();
        map.put("result",obj);
        ObjectMapper mapper = new ObjectMapper();
        String result = mapper.writeValueAsString(map);
        return result;
    }
    
}

十,JsonResult.java


package com.hao.common.result;

public class JsonResult {
    private boolean success;
    private String status;
    private String msg;
    private Object obj;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }
}

十一,MyMetaObjectHandler.java

package com.hao.common;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 自定义填充处理器
 */
public class MyMetaObjectHandler extends MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("ctime", new Date(), metaObject);
    }

    @Override
    public boolean openUpdateFill() {
        return false;
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 关闭更新填充、这里不执行
    }
}

十二,pom.xml文件




  4.0.0

  com.haohao
  SpringMVCMybatisMysqlMaven
  1.0-SNAPSHOT
  war

  SpringMVCMybatisMysqlMaven Maven Webapp
  
  http://www.example.com


  
    UTF-8
    5.0.0.RELEASE
    4.12
    1.1.0
    1.2.8
    2.1.9
    5.1.38
    1.2.17
    1.7.19
    1.8.8
    1.3.1
    1.2
    
    
  
  
    
    
      junit
      junit
      ${junit.version}
      test
    
    
      net.sourceforge.jexcelapi
      jxl
      2.6.10
    
    
    
      org.springframework
      spring-core
      ${spring.version}
      jar
      compile
    
    
      org.springframework
      spring-context
      ${spring.version}
      jar
      compile
    
    
      org.springframework
      spring-context-support
      ${spring.version}
      jar
      compile
    
    
      org.springframework
      spring-tx
      ${spring.version}
      jar
      compile
    
    
      org.springframework
      spring-aop
      ${spring.version}
      jar
      compile
    
    
      org.springframework
      spring-beans
      ${spring.version}
      jar
      compile
    
    
      org.springframework
      spring-jdbc
      ${spring.version}
      jar
      compile
    

    
    
      org.springframework
      spring-web
      ${spring.version}
      jar
      compile
    
    
      org.springframework
      spring-webmvc
      ${spring.version}
      jar
      compile
    

    
    
      org.aspectj
      aspectjweaver
      ${aspectjweaver.version}
    

    
    
      commons-fileupload
      commons-fileupload
      ${fileupload.version}
    

    
      javax.servlet
      jstl
      ${jstl.version}
    

    
    
      com.baomidou
      mybatis-plus
      ${mybaitsplus.version}
    
    
    
      org.mybatis.caches
      mybatis-ehcache
      1.1.0
    

    
    
        mysql
        mysql-connector-java
        ${mysql.version}
    
    
    
    
      com.alibaba
      druid
      ${druid.version}
    

    
    
      com.alibaba
      fastjson
      ${fastjson.version}
    
    
      com.fasterxml.jackson.core
      jackson-databind
      2.9.6
    
    
    
      log4j
      log4j
      ${log4j.version}
    
    
      org.slf4j
      slf4j-api
      ${slf4j.version}
    
    
      org.slf4j
      slf4j-log4j12
      ${slf4j.version}
    

    
      org.springframework
      spring-test
      ${spring.version}
    
  
  
    party
    
      
        org.apache.maven.plugins
        maven-compiler-plugin
        
          1.8
          1.8
        
      
    
  

十三,代码生成器 CodeGenerateWithMethods.java

package com.hao.test;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;

public class CodeGenerateWithMethods {
    @Test
    public void generate(){
        // 指定包名
        String packageName = "com.hao.system";
        // 作者
        String author = "";
        // 指定生成的表名
        String[] tableNames = new String[]{"system_user"};
        // 数据库连接地址
        String databaseUrl = "jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
        String jdbc = "com.mysql.jdbc.Driver";
        // 数据库名称
        String databaseUserName = "root";
        // 数据库密码
        String databasePassword = "root";
        // 生成后端代码路径
        String backClassPath = getOutPutDir("SpringMVCMybatisMysqlMaven");

        // 模板路径
        String  templatePath = "/templates/myController.java.vm";
        // 执行代码
        generateBackCode(packageName,tableNames,author, backClassPath, databaseUrl,databaseUserName,databasePassword, templatePath, jdbc);
    }

    // 代码生成器
    public void generateBackCode(String packageName,
                                 String[] tableNames, String author,
                                 String backClassPath, String databaseUrl,
                                 String databaseUserName, String databasePassword, String templatePath, String jdbc
    ){
        new AutoGenerator()
                // 全局变量配置
                .setGlobalConfig(
                        new GlobalConfig()
                                .setBaseColumnList(true)
                                .setBaseResultMap(true)
                                .setActiveRecord(false)
                                // 设置作者
                                .setAuthor(author)
                                // 设置输出路径
                                .setOutputDir(backClassPath)
                                .setFileOverride(true)
                                .setServiceName("%sService")
                )
                // 配置数据源
                .setDataSource(
                        new DataSourceConfig().setDbType(DbType.MYSQL)/*DbType.SQL_SERVER*/
                                .setUrl(databaseUrl)
                                // 数据库名称
                                .setUsername(databaseUserName)
                                // 数据库密码
                                .setPassword(databasePassword)
                                // 数据库驱动jdbc
                                .setDriverName(jdbc)
                )
                // 策略配置
                .setStrategy(
                        new StrategyConfig()
                                // 全局大写命名 ORACLE 注意
                                .setCapitalMode(true)
                                .setEntityLombokModel(false)
                                // 表名、字段名、是否使用下划线命名(默认 false)
                                .setDbColumnUnderline(true)
                                //从数据库表到文件的命名策略
                                .setNaming(NamingStrategy.underline_to_camel)
                                //需要生成的的表名,多个表名传数组
                                .setInclude(tableNames)
                )
                .setPackageInfo(
                        new PackageConfig()
                                .setParent(packageName)
                                .setXml("mapper")
                                .setMapper("dao")
                                .setController("controller")
                                .setEntity("entity")
                )
                .setTemplate(
                        new TemplateConfig()
                                .setController(templatePath)
                )
                .execute();
    }

    /**
     * 获取项目路径
     * @param projectName
     * @return String
     * @Author QiHao
     */
    private String getOutPutDir(String projectName) {
        String path = this.getClass().getClassLoader().getResource("").getPath();
        int index = path.indexOf(projectName);
        return path.substring(1, index) + projectName + "/src/main/java/";
    }
}

你可能感兴趣的:(脚手架)