一键生成Spring MVC + MyBatis + maven项目

首先创建一个新的maven项目,在src/main/java创建一个类Test

然后在Test复制以下代码:

import java.io.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test {
    //列如配置到com.wbg.ssm包下  程序会自动添加daocontrollerserviceentity
    final static String Package = "com.nf147.chen";  //包名格式
    final static String database = "shop";   //数据库名称
    final static String user = "root";//数据库账号
    final static String password = "123456";//数据库密码
    //---------------^^^^^^^^^^^^^配置上面四项^^^^^^^^^^^^^^^^^--------------------------
    final static String dburl = "jdbc:mariadb://localhost:3306/"+database;  //服务器地址
    final static String dbdriver = "org.mariadb.jdbc.Driver"; //驱动
    public static void main(String[] args) throws Exception {
        System.out.println("1、第一次配置");
        System.out.println("2、第二次配置");
        System.out.print("请输入配置:");
        Scanner scanner = new Scanner(System.in);
        String c = scanner.next();
        if("1".equals(c)){
            System.out.println("开始第一次配置");
            createStart();
            System.out.println("开始第一次配置完成");
        }
        else if("2".equals(c)){
            System.out.println("开始第二次配置");
            for (String table : TBlist()) {
                createStart(tables(table));
            }
            //创建Request
            System.out.println("创建Request");
            createFile(new File(srcPackage + "util\Result.java"), createResult());
            System.out.println("开始第二次配置完成");
        }else{
            System.out.printf("只能输入1、2选项");
        }
    }

    //获取当前项目的路径
    public static String url = System.getProperty("user.dir");
    //包的路径
    public static String srcPackage = url + "/src/main/java/"+Package.replace(".","/")+"/";
    private static String tablename;
    private String[] colnames; // 列名数组
    private String[] colTypes; // 列名类型数组
    private int[] colSizes; // 列名大小数组
    static void createStart() {
        System.out.println("开始配置pom.xml");
        System.out.println(configPomXml(url));
        url = url + File.separator + "src" + File.separator + "main";
        System.out.println("开始配置resources目录");
        createResources(url + File.separator + "resources");
        System.out.println("完成配置resources目录");
        System.out.println("开始配置webapp目录");
        createWebapp(url + File.separator + "webapp");
        System.out.println("完成配置webapp目录");
    }

    //***********************Resources************************

    /**
     * 创建四个配置文件
     * dbc.properties
     * log4j.properties
     * mybatis-config.xml
     * spring-web.xml
     *
     * @return
     */
    static boolean createResources(String url) {
        if (createJdbcProperties(url)) {
            System.out.println("jdbc.properties配置成功");
        } else {
            System.out.println("jdbc.properties配置失败");
        }
        if (log4jProperties(url)) {
            System.out.println("log4j.properties配置成功");
        } else {
            System.out.println("log4j.properties配置失败");
        }
        if (mybatisConfig(url)) {
            System.out.println("mybatis-config.xml配置成功");
        } else {
            System.out.println("mybatis-config.xml配置失败");
        }
        if (springWeb(url)) {
            System.out.println("spring-web.xml配置成功");
        } else {
            System.out.println("spring-web.xml配置失败");
        }
        if (generatorConfig(url)) {
            System.out.println("generatorConfig.xml配置成功");
        } else {
            System.out.println("generatorConfig.xml配置失败");
        }

        //
esourcesspring
        if (springDao(url + File.separator + "spring")) {
            System.out.println("spring-dao.xml配置成功");
        } else {
            System.out.println("spring-dao.xml配置失败");
        }
        //
esourcesspring
        if (springService(url + File.separator + "spring")) {
            System.out.println("spring-service.xml配置成功");
        } else {
            System.out.println("spring-service.xml配置失败");
        }

        return true;
    }

    /**
     * 创建jdbc.properties配置文件
     *
     * @param url 路径
     * @return
     */
    static boolean createJdbcProperties(String url) {
        File file = new File(url, "jdbc.properties");
        String context = "jdbc.driver=org.mariadb.jdbc.Driver
" +
                "jdbc.url=jdbc:mariadb://localhost:3306/" + database + "
" +
                "jdbc.username="+user+"
" +
                "jdbc.password="+password+"";
        return createFile(file, context);
    }

    /**
     * 创建log4j.properties日志文件
     *
     * @param url 路径
     * @return
     */
    static boolean log4jProperties(String url) {
        File file = new File(url, "log4j.properties");

        String context = "# Global logging configuration
" +
                "log4j.rootLogger=ERROR, ooo
" +
                "
" +
                "# MyBatis logging configuration...
" +
                "log4j.logger." + Package + ".dao=DEBUG
" +
                "
" +
                "# 规则1,名字为 ooo,向标准输出 System.err/out
" +
                "log4j.appender.ooo=org.apache.log4j.ConsoleAppender
" +
                "log4j.appender.ooo.layout=org.apache.log4j.PatternLayout
" +
                "log4j.appender.ooo.layout.ConversionPattern=%5p [%t] ~ %m%n
";
        return createFile(file, context);
    }

    /**
     * 创建mybatis-config.xml配置文件
     *
     * @param url 路径
     * @return
     */
    static boolean mybatisConfig(String url) {
        File file = new File(url, "mybatis-config.xml");

        String context = "<?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获取数据库自增主键值 -->
" +
                "        <setting name="useGeneratedKeys" value="true" />
" +
                "        <!-- 使用列别名替换列名 默认:true -->
" +
                "        <setting name="useColumnLabel" value="true" />
" +
                "        <!-- 开启驼峰命名转换:Table {create_time} -> Entity {createTime} -->
" +
                "        <setting name="mapUnderscoreToCamelCase" value="true" />
" +
                "    </settings>
" +
                "
" +
                "    <plugins>
" +
                "        <plugin interceptor="com.github.pagehelper.PageInterceptor" />
" +
                "    </plugins>
" +
                "</configuration>";
        return createFile(file, context);
    }

    /**
     * 创建spring-web.xml配置文件
     *
     * @return
     */
    static boolean springWeb(String url) {
        File file = new File(url, "spring-web.xml");

        String context = "<?xml version="1.0" encoding="UTF-8"?>
" +
                "<beans xmlns="http://www.springframework.org/schema/beans"
" +
                "       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
" +
                "       xmlns:context="http://www.springframework.org/schema/context"
" +
                "       xmlns:mvc="http://www.springframework.org/schema/mvc"
" +
                "       xsi:schemaLocation="http://www.springframework.org/schema/beans
" +
                "	http://www.springframework.org/schema/beans/spring-beans.xsd
" +
                "	http://www.springframework.org/schema/context
" +
                "	http://www.springframework.org/schema/context/spring-context.xsd
" +
                "	http://www.springframework.org/schema/mvc
" +
                "	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
" +
                "    <!-- 配置SpringMVC -->
" +
                "    <!-- 1.开启SpringMVC注解模式 -->
" +
                "    <!-- 简化配置:
" +
                "        (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
" +
                "        (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持
" +
                "    -->
" +
                "    <mvc:annotation-driven />
" +
                "
" +
                "    <!-- 2.静态资源默认servlet配置
" +
                "        (1)加入对静态资源的处理:js,gif,png
" +
                "        (2)允许使用"/"做整体映射
" +
                "     -->
" +
                "    <mvc:default-servlet-handler/>
" +
                "
" +
                "    <!-- 3.配置jsp 显示ViewResolver -->
" +
                "  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
" +
                "        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
" +
                "        <property name="prefix" value="/WEB-INF/jsp/" />
" +
                "        <property name="suffix" value=".jsp" />
" +
                "    </bean>
" +
                "    <!-- 4.扫描web相关的bean -->
" +
                "    <context:component-scan base-package="" + Package + ".controller" />
" +
                "</beans>";
        return createFile(file, context);
    }

    /**
     * 创建spring-dao.xml配置文件
     *
     * @param url 路径
     * @return
     */
    static boolean springDao(String url) {
        File file = new File(url, "spring-dao.xml");
        String context = "<?xml version="1.0" encoding="UTF-8"?>
" +
                "<beans xmlns="http://www.springframework.org/schema/beans"
" +
                "       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
" +
                "       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
" +
                "       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
" +
                "
" +
                "
" +
                "
" +
                "    <!-- 配置整合mybatis过程 -->
" +
                "    <!-- 1.配置数据库相关参数properties的属性:${url} -->
" +
                "    <context:property-placeholder location="classpath:jdbc.properties" />
" +
                "
" +
                "    <!-- 2.数据库连接池 -->
" +
                "    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
" +
                "        <property name="driverClass" value="${jdbc.driver}" />
" +
                "        <property name="jdbcUrl" value="${jdbc.url}" />
" +
                "        <property name="user" value="${jdbc.username}" />
" +
                "        <property name="password" value="${jdbc.password}" />
" +
                "
" +
                "        <!-- c3p0连接池的私有属性 -->
" +
                "        <property name="maxPoolSize" value="30" />
" +
                "        <property name="minPoolSize" value="10" />
" +
                "        <!-- 关闭连接后不自动commit -->
" +
                "        <property name="autoCommitOnClose" value="false" />
" +
                "        <!-- 获取连接超时时间 -->
" +
                "        <property name="checkoutTimeout" value="10000" />
" +
                "        <!-- 当获取连接失败重试次数 -->
" +
                "        <property name="acquireRetryAttempts" value="2" />
" +
                "    </bean>
" +
                "
" +
                "    <!-- 3.配置SqlSessionFactory对象 -->
" +
                "    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
" +
                "        <!-- 注入数据库连接池 -->
" +
                "        <property name="dataSource" ref="dataSource" />
" +
                "        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
" +
                "        <property name="configLocation" value="classpath:mybatis-config.xml" />
" +
                "        <!-- 扫描entity包 使用别名 -->
" +
                "        <property name="typeAliasesPackage" value="" + Package + ".entity" />
" +
                "        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
" +
                "        <property name="mapperLocations" value="classpath:mapper/*.xml" />
" +
                "    </bean>
" +
                "
" +
                "    <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
" +
                "    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
" +
                "        <!-- 注入sqlSessionFactory -->
" +
                "        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
" +
                "        <!-- 给出需要扫描Dao接口包 -->
" +
                "        <property name="basePackage" value="" + Package + ".dao" />
" +
                "    </bean>
" +
                "
" +
                "    <!--配置声明式事务管理-->
" +
                "    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
" +
                "        <property name="dataSource" ref="dataSource" />
" +
                "    </bean>
" +
                "    <tx:annotation-driven proxy-target-class="true" />
" +
                "
" +
                "</beans>";
        return createFile(file, context);
    }

    /**
     * 创建spring-service.xml配置文件
     *
     * @param url 路径
     * @return
     */
    static boolean springService(String url) {
        File file = new File(url, "spring-service.xml");
        String context = "<?xml version="1.0" encoding="UTF-8"?>
" +
                "<beans xmlns="http://www.springframework.org/schema/beans"
" +
                "       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
" +
                "       xmlns:context="http://www.springframework.org/schema/context"
" +
                "       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
" +
                "       xmlns:aop="http://www.springframework.org/schema/aop"
" +
                "       xsi:schemaLocation="http://www.springframework.org/schema/beans
" +
                "	http://www.springframework.org/schema/beans/spring-beans.xsd
" +
                "	http://www.springframework.org/schema/context
" +
                "	http://www.springframework.org/schema/context/spring-context.xsd
" +
                " http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
" +
                "    <!-- 扫描service包下所有使用注解的类型 -->
" +
                "    <context:component-scan base-package="" + Package + ".service" />
" +
                "    <mvc:annotation-driven />
" +
                "    <!-- 启用 aspectj 方式 AOP-->
" +
                "    <aop:aspectj-autoproxy proxy-target-class="true" />
" +
                "</beans>";
        return createFile(file, context);
    }

    /**
     * 创建generatorConfig.xml配置文件
     * @param url
     * @return
     */
    static boolean generatorConfig(String url) {
        File file = new File(url, "generatorConfig.xml");
        String context = "<?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>
" +
                "    <!--jdbc 驱动包,等-->
" +
                "    <!--<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />-->
" +
                "
" +
                "    <context id="sss" targetRuntime="MyBatis3Simple">
" +
                "
" +
                "        <commentGenerator>
" +
                "            <property name="suppressAllComments" value="true" />
" +
                "        </commentGenerator>
" +
                "
" +
                "        <jdbcConnection driverClass="org.mariadb.jdbc.Driver"
" +
                "                        connectionURL="jdbc:mariadb://localhost/"+database+""
" +
                "                        userId=""+user+""
" +
                "                        password=""+password+"">
" +
                "        </jdbcConnection>
" +
                "
" +
                "        <javaModelGenerator targetPackage=""+Package+".entity" targetProject="src/main/java">
" +
                "            <property name="trimStrings" value="true" />
" +
                "        </javaModelGenerator>
" +
                "
" +
                "        <sqlMapGenerator targetPackage="mappers"  targetProject="src/main/resources">
" +
                "        </sqlMapGenerator>
" +
                "
" +
                "        <javaClientGenerator type="XMLMAPPER" targetPackage=""+Package+".dao"  targetProject="src/main/java">
" +
                "        </javaClientGenerator>
" +
                "
" +
                "        <table tableName="%">
" +
                "            <!-- false:驼峰命名-->
" +
                "            <property name="useActualColumnNames" value="false"/>
" +
                "        </table>
" +
                "    </context>
" +
                "</generatorConfiguration>";
        return createFile(file, context);
    }


    //***********************webapp************************
    static boolean createWebapp(String url) {
        if (webXml(url + File.separator + "WEB-INF")) {
            System.out.println("web.xml配置成功");
        } else {
            System.out.println("web.xml配置失败");
        }
        createCSSJSDirectory(url + File.separator);
        return true;
    }

    /**
     * 创建WEB-INFweb.xml配置文件
     *
     * @param url 路径
     * @return
     */
    static boolean webXml(String url) {
        File file = new File(url, "web.xml");

        File f = new File(url,"/jsp");
        f.mkdirs();
        String context = "<?xml version="1.0" encoding="UTF-8"?>
" +
                "<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
" +
                "         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
" +
                "         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
" +
                "         version="4.0">
" +
                "
" +
                "    <display-name>自动生成</display-name>
" +
                "
" +
                "    <!--解决中文乱码-->
" +
                "    <filter>
" +
                "        <filter-name>encodingFilter</filter-name>
" +
                "        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
" +
                "        <async-supported>true</async-supported>
" +
                "        <init-param>
" +
                "            <param-name>encoding</param-name>
" +
                "            <param-value>UTF-8</param-value>
" +
                "        </init-param>
" +
                "
" +
                "    </filter>
" +
                "    <filter-mapping>
" +
                "        <filter-name>encodingFilter</filter-name>
" +
                "        <url-pattern>/*</url-pattern>
" +
                "    </filter-mapping>
" +
                "
" +
                "    <!--配置 Spring 的容器-->
" +
                "    <context-param>
" +
                "        <param-name>contextConfigLocation</param-name>
" +
                "        <param-value>classpath:spring/spring-*.xml</param-value>
" +
                "    </context-param>
" +
                "    <listener>
" +
                "        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
" +
                "    </listener>
" +
                "
" +
                "    <!--配置 MVC 容器-->
" +
                "    <!--将所有的请求都交给 Spring MVC 处理-->
" +
                "    <servlet>
" +
                "        <servlet-name>app</servlet-name>
" +
                "        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
" +
                "        <init-param>
" +
                "            <param-name>contextConfigLocation</param-name>
" +
                "            <param-value>classpath:spring-web.xml</param-value>
" +
                "        </init-param>
" +
                "    </servlet>
" +
                "    <servlet-mapping>
" +
                "        <servlet-name>app</servlet-name>
" +
                "        <url-pattern>/</url-pattern>
" +
                "    </servlet-mapping>
" +
                "</web-app>";


        return createFile(file, context);
    }

    /**
     * 创建css和js
     *
     * @param url 路径
     */
    static boolean createCSSJSDirectory(String url) {
        File fcss = new File(url + "css");
        if (fcss.mkdirs()) {
            System.out.println("成功创建css文件夹");
        }
        File fjs = new File(url + "js");
        if (fjs.mkdirs()) {
            System.out.println("成功创建js文件夹");
        }

        return true;
    }

    /**
     * @param file    创建的文件
     * @param context 文件里面的内容
     */
    static boolean createFile(File file, String context) {
        //获取文件
        File parent = file.getParentFile();
        //如果是目录
        if (parent != null) {
            //创建目录
            parent.mkdirs();
        }
        try {
            //创建文件
            file.createNewFile();
            FileWriter fileWriter = null;
            try {
                fileWriter = new FileWriter(file);
                fileWriter.write(context);
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                return false;
            }
        } catch (IOException e) {
            System.out.println("创建文件失败:" + e.getMessage());
        }
        return true;
    }


    //***********************pom.xml************************

    /**
     * 配置pom.xml文件
     *
     * @param url 路径
     */
    static String configPomXml(String url) {
        File file = new File(url, "pom.xml");
        InputStream inputStream = null;
        byte b[] = new byte[Integer.parseInt(String.valueOf(file.length()))];
        StringBuffer stringBuffer = null;
        try {
            inputStream = new FileInputStream(file);
            inputStream.read(b);
            inputStream.close();
            stringBuffer = new StringBuffer(new String(b));
            stringBuffer.replace(Integer.parseInt(String.valueOf(file.length())) - 10, Integer.parseInt(String.valueOf(file.length())), "");
            stringBuffer.append(pomContext());
        } catch (Exception e) {
            return "程序出错,请重试 -- pom.xml文件配置失败";
        }
        if (createFile(file, stringBuffer.toString())) {
            return "pom.xml文件配置完成";
        }
        return "pom.xml文件配置失败";
    }

    /**
     * pom.xml配置文件需要加的配置
     *
     * @return
     */
    static String pomContext() {
        return "<!--打包-->
" +
                "    <packaging>war</packaging>
" +
                "    <!--设置编码-->
" +
                "    <properties>
" +
                "        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
" +
                "        <maven.compiler.source>1.8</maven.compiler.source>
" +
                "        <maven.compiler.target>1.8</maven.compiler.target>
" +
                "        <spring.version>5.1.0.RELEASE</spring.version>
" +
                "    </properties>
" +
                "    <!--引入文件-->
" +
                "    <dependencies>
" +
                "        <!-- Spring Web MVC -->
" +
                "        <dependency>
" +
                "            <groupId>org.springframework</groupId>
" +
                "            <artifactId>spring-web</artifactId>
" +
                "            <version>${spring.version}</version>
" +
                "        </dependency>
" +
                "        <dependency>
" +
                "            <groupId>org.springframework</groupId>
" +
                "            <artifactId>spring-webmvc</artifactId>
" +
                "            <version>${spring.version}</version>
" +
                "        </dependency>
" +
                "
" +
                "        <!-- servlet 系列的支持 -->
" +
                "        <dependency>
" +
                "            <groupId>javax</groupId>
" +
                "            <artifactId>javaee-api</artifactId>
" +
                "            <version>8.0</version>
" +
                "            <scope>provided</scope>
" +
                "        </dependency>
" +
                "        <dependency>
" +
                "            <groupId>javax.servlet</groupId>
" +
                "            <artifactId>jstl</artifactId>
" +
                "            <version>1.2</version>
" +
                "        </dependency>
" +
                "
" +
                "        <dependency>
" +
                "            <groupId>com.github.pagehelper</groupId>
" +
                "            <artifactId>pagehelper</artifactId>
" +
                "            <version>5.1.7</version>
" +
                "        </dependency>
" +
                "
" +
                "        <!-- Springframework -->
" +
                "        <dependency>
" +
                "            <groupId>org.springframework</groupId>
" +
                "            <artifactId>spring-context</artifactId>
" +
                "            <version>${spring.version}</version>
" +
                "        </dependency>
" +
                "        <dependency>
" +
                "            <groupId>org.springframework</groupId>
" +
                "            <artifactId>spring-jdbc</artifactId>
" +
                "            <version>${spring.version}</version>
" +
                "        </dependency>
" +
                "        <dependency>
" +
                "            <groupId>org.springframework</groupId>
" +
                "            <artifactId>spring-aop</artifactId>
" +
                "            <version>${spring.version}</version>
" +
                "        </dependency>
" +
                "        <dependency>
" +
                "            <groupId>org.aspectj</groupId>
" +
                "            <artifactId>aspectjweaver</artifactId>
" +
                "            <version>1.9.1</version>
" +
                "        </dependency>
" +
                "
" +
                "        <!-- MyBatis -->
" +
                "        <dependency>
" +
                "            <groupId>org.mybatis</groupId>
" +
                "            <artifactId>mybatis</artifactId>
" +
                "            <version>3.4.6</version>
" +
                "        </dependency>
" +
                "        <dependency>
" +
                "            <groupId>org.mybatis</groupId>
" +
                "            <artifactId>mybatis-spring</artifactId>
" +
                "            <version>1.3.2</version>
" +
                "        </dependency>
" +
                "
" +
                "        <!-- 数据库驱动以及数据库连接池-->
" +
                "        <dependency>
" +
                "            <groupId>org.mariadb.jdbc</groupId>
" +
                "            <artifactId>mariadb-java-client</artifactId>
" +
                "            <version>2.3.0</version>
" +
                "        </dependency>
" +
                "        <dependency>
" +
                "            <groupId>com.mchange</groupId>
" +
                "            <artifactId>c3p0</artifactId>
" +
                "            <version>0.9.5.2</version>
" +
                "        </dependency>
" +
                "
" +
                "        <!-- 日志框架 -->
" +
                "        <dependency>
" +
                "            <groupId>log4j</groupId>
" +
                "            <artifactId>log4j</artifactId>
" +
                "            <version>1.2.17</version>
" +
                "        </dependency>
" +
                "
" +
                "        <!-- 通用工具 -->
" +
                "        <dependency>
" +
                "            <groupId>com.fasterxml.jackson.core</groupId>
" +
                "            <artifactId>jackson-databind</artifactId>
" +
                "            <version>2.9.7</version>
" +
                "        </dependency>
" +
                "
" +
                "        <!-- 单元测试 -->
" +
                "        <dependency>
" +
                "            <groupId>org.springframework</groupId>
" +
                "            <artifactId>spring-test</artifactId>
" +
                "            <version>${spring.version}</version>
" +
                "            <scope>test</scope>
" +
                "        </dependency>
" +
                "
" +
                "        <dependency>
" +
                "            <groupId>junit</groupId>
" +
                "            <artifactId>junit</artifactId>
" +
                "            <version>4.12</version>
" +
                "            <scope>test</scope>
" +
                "        </dependency>
" +
                "    </dependencies>
" +
                "    <build>
" +
                "        <finalName>contact</finalName>
" +
                "        <plugins>
" +
                "            <plugin>
" +
                "                <groupId>org.mybatis.generator</groupId>
" +
                "                <artifactId>mybatis-generator-maven-plugin</artifactId>
" +
                "                <version>1.3.7</version>
" +
                "                <dependencies>
" +
                "                    <dependency>
" +
                "                        <groupId>org.mariadb.jdbc</groupId>
" +
                "                        <artifactId>mariadb-java-client</artifactId>
" +
                "                        <version>2.3.0</version>
" +
                "                    </dependency>
" +
                "                </dependencies>
" +
                "            </plugin>
" +
                "        </plugins>
" +
                "
" +
                "        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
" +
                "            <plugins>
" +
                "                <plugin>
" +
                "                    <artifactId>maven-clean-plugin</artifactId>
" +
                "                    <version>3.0.0</version>
" +
                "                </plugin>
" +
                "                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
" +
                "                <plugin>
" +
                "                    <artifactId>maven-resources-plugin</artifactId>
" +
                "                    <version>3.0.2</version>
" +
                "                </plugin>
" +
                "                <plugin>
" +
                "                    <artifactId>maven-compiler-plugin</artifactId>
" +
                "                    <version>3.7.0</version>
" +
                "                </plugin>
" +
                "                <plugin>
" +
                "                    <artifactId>maven-surefire-plugin</artifactId>
" +
                "                    <version>2.20.1</version>
" +
                "                </plugin>
" +
                "                <plugin>
" +
                "                    <artifactId>maven-war-plugin</artifactId>
" +
                "                    <version>3.2.0</version>
" +
                "                </plugin>
" +
                "                <plugin>
" +
                "                    <artifactId>maven-install-plugin</artifactId>
" +
                "                    <version>2.5.2</version>
" +
                "                </plugin>
" +
                "                <plugin>
" +
                "                    <artifactId>maven-deploy-plugin</artifactId>
" +
                "                    <version>2.8.2</version>
" +
                "                </plugin>
" +
                "            </plugins>
" +
                "        </pluginManagement>
" +
                "    </build>

" +
                "</project>";
    }


    //-------------------------------------------------------
    /**
     * 获取指定数据库中包含的表 TBlist
     *
     * @return 返回所有表名(将表名放到一个集合中)
     * @throws Exception
     * @time 2017年7月14日下午5:54:52
     * @packageName com.util
     */
    public static List<String> TBlist() throws Exception {
        // 访问数据库 采用 JDBC方式
        Class.forName(dbdriver);

        Connection con = DriverManager.getConnection(dburl, user, password);

        DatabaseMetaData md = con.getMetaData();

        List<String> list = null;

        ResultSet rs = md.getTables(null, null, null, null);
        if (rs != null) {
            list = new ArrayList<String>();
        }
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            list.add(tableName);
        }
        rs = null;
        md = null;
        con = null;
        return list;
    }

    /**
     * 把输入字符串的首字母改成大写
     *
     * @param str
     * @return
     */
    private static String initcap(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        return new String(ch);
    }

    /**
     * 把输入字符串的首字母改成小写
     *
     * @param str
     * @return
     */
    private static String initlow(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'A' && ch[0] <= 'Z') {
            ch[0] = (char) (ch[0] + 32);
        }
        return new String(ch);
    }

    //首字母转换和下划线转换
    private static String tables(String table) {
        String[] tables = table.split("_");
        table = "";
        for (String s : tables) {
            table += initcap(s);
        }
        return table;
    }
    /**
     * 创建Dao
     */
    private static String createDao(String tableName) {
        String service = "package "+Package+".dao;
" +
                "
" +
                "import "+Package+".entity."+tableName+";
" +
                "import org.springframework.stereotype.Repository;
" +
                "
" +
                "import java.util.List;
" +
                "
" +
                "@Repository
" +
                "public interface "+tableName+"Mapper {
" +
                "    int deleteByPrimaryKey(int id);
" +
                "
" +
                "    int insert("+tableName+" "+initlow(tableName)+");
" +
                "
" +
                "    "+tableName+" selectByPrimaryKey(int id);
" +
                "
" +
                "    List<"+tableName+"> selectAll();
" +
                "
" +
                "    int updateByPrimaryKey("+tableName+" "+initlow(tableName)+");
" +
                "}";
        return service;
    }

    /**
     * 创建Service
     *
     * @param tableName 数据库表
     */
    private static String createService(String tableName) {
        String service = "package "+Package+".service;
" +
                "
" +
                "import "+Package+".entity." + tableName + ";
" +
                "
" +
                "import java.util.List;
" +
                "
" +
                "public interface " + tableName + "Service {
" +
                "
" +
                "    int deleteByPrimaryKey(int id);
" +
                "
" +
                "    int insert(" + tableName + " " + initlow(tableName) + ");
" +
                "
" +
                "    " + tableName + " selectByPrimaryKey(int id);
" +
                "
" +
                "    List<" + tableName + "> selectAll();
" +
                "
" +
                "    int updateByPrimaryKey(" + tableName + " " + initlow(tableName) + ");
" +
                "}";
        return service;
    }

    /**
     * 创建ServiceImpl
     *
     * @param tableName 数据库表
     */
    private static String createServiceImpl(String tableName) {
        String serviceImpl = "package "+Package+".service.impl;
" +
                "
" +
                "import "+Package+".dao." + tableName + "Mapper;
" +
                "import "+Package+".entity." + tableName + ";
" +
                "import "+Package+".service." + tableName + "Service;
" +
                "import org.springframework.beans.factory.annotation.Autowired;
" +
                "import org.springframework.stereotype.Service;
" +
                "
" +
                "import java.util.List;
" +
                "
" +
                "@Service
" +
                "public class " + tableName + "ServiceImpl implements " + tableName + "Service {
" +
                "
" +
                "    @Autowired
" +
                "    private " + tableName + "Mapper " + initlow(tableName) + "Mapper;
" +
                "
" +
                "    @Override
" +
                "    public int deleteByPrimaryKey(int id) {
" +
                "        return " + initlow(tableName) + "Mapper.deleteByPrimaryKey(id);
" +
                "    }
" +
                "
" +
                "    @Override
" +
                "    public int insert(" + tableName + " " + initlow(tableName) + ") {
" +
                "        return " + initlow(tableName) + "Mapper.insert(" + initlow(tableName) + ");
" +
                "    }
" +
                "
" +
                "    @Override
" +
                "    public " + tableName + " selectByPrimaryKey(int id) {
" +
                "        return " + initlow(tableName) + "Mapper.selectByPrimaryKey(id);
" +
                "    }
" +
                "
" +
                "    @Override
" +
                "    public List<" + tableName + "> selectAll() {
" +
                "        return " + initlow(tableName) + "Mapper.selectAll();
" +
                "    }
" +
                "
" +
                "    @Override
" +
                "    public int updateByPrimaryKey(" + tableName + " " + initlow(tableName) + ") {
" +
                "        return " + initlow(tableName) + "Mapper.updateByPrimaryKey(" + initlow(tableName) + ");
" +
                "    }
" +
                "}
";
        return serviceImpl;
    }

    /**
     * 创建Controller
     *
     * @param tableName 数据库表
     */
    private static String createController(String tableName) {
        String controller = "package "+Package+".controller;
" +
                "import "+Package+".entity." + tableName + ";
" +
                "import "+Package+".service." + tableName + "Service;
" +
                "import "+Package+".util.Result;
" +
                "import org.springframework.beans.factory.annotation.Autowired;
" +
                "import org.springframework.web.bind.annotation.*;
" +
                "import java.util.List;
" +
                "
" +
                "@RestController
" +
                "@RequestMapping("/" + initlow(tableName) + "")
" +
                "public class " + tableName + "Controller {
" +
                "    @Autowired
" +
                "    private " + tableName + "Service " + initlow(tableName) + "Service;
" +
                "
" +
                "    @GetMapping("/deleteByPrimaryKey")
" +
                "    public Result deleteByPrimaryKey(int id) {
" +
                "        try {
" +
                "
" +
                "            return " + initlow(tableName) + "Service.deleteByPrimaryKey(id) > 0 ? new Result().successMessage("删除成功") : Result.error("删除失败");
" +
                "        } catch (Exception ex) {
" +
                "            return new Result().error("ex.getMessage()");
" +
                "        }
" +
                "    }
" +
                "
" +
                "    @PostMapping("/insert")
" +
                "    public Result insert(@RequestBody " + tableName + " " + initlow(tableName) + ") {
" +
                "        try {
" +
                "            return " + initlow(tableName) + "Service.insert(" + initlow(tableName) + ") > 0 ? new Result().successMessage("添加成功!") : Result.error("添加失败!");
" +
                "        } catch (Exception ex) {
" +
                "            return new Result().error("ex.getMessage()");
" +
                "        }
" +
                "
" +
                "    }
" +
                "
" +
                "    @GetMapping("/selectByPrimaryKey")
" +
                "    public Result selectByPrimaryKey(int id) {
" +
                "        try {
" +
                "            " + tableName + " " + initlow(tableName) + "1 = " + initlow(tableName) + "Service.selectByPrimaryKey(id);
" +
                "            if (" + initlow(tableName) + "1 == null) {
" +
                "                return new Result().successMessage("无数据");
" +
                "            } else {
" +
                "                return new Result().success(" + initlow(tableName) + "1);
" +
                "            }
" +
                "        } catch (Exception ex) {
" +
                "            return new Result().error("ex.getMessage()");
" +
                "        }
" +
                "    }
" +
                "
" +
                "    @GetMapping("/selectAll")
" +
                "    public Result selectAll() {
" +
                "        //public Result selectAll(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
" +
                "        try {
" +
                "            //分页
" +
                "            //PageHelper.startPage(pageNum, pageSize);
" +
                "            List<" + tableName + "> list = " + initlow(tableName) + "Service.selectAll();
" +
                "            if (list == null) {
" +
                "                return new Result().successMessage("无数据");
" +
                "            } else {
" +
                "                // return new Result().success(list, " + initlow(tableName) + "Service.count(""));
" +
                "                return new Result().success(list);
" +
                "            }
" +
                "        } catch (Exception ex) {
" +
                "            return new Result().error("ex.getMessage()");
" +
                "        }
" +
                "    }
" +
                "
" +
                "    @PostMapping(value = "/updateByPrimaryKey")
" +
                "    public Result updateByPrimaryKey(@RequestBody " + tableName + " " + initlow(tableName) + ") {
" +
                "        try {
" +
                "            return " + initlow(tableName) + "Service.updateByPrimaryKey(" + initlow(tableName) + ") > 0 ? new Result().successMessage("修改成功") : Result.error("修改失败");
" +
                "        } catch (Exception ex) {
" +
                "            return new Result().error("ex.getMessage()");
" +
                "        }
" +
                "
" +
                "
" +
                "    }
" +
                "}
";
        return controller;
    }
    /**
     * 创建util
     *
     */
    private static String createResult() {
        String controller = "package "+Package+".util;
" +
                "
" +
                "public class Result {
" +
                "
" +
                " /* 根据Constants 常量 进行返回编码
" +
                "    public static final int SUCCESS_CODE = 200;
" +
                "    public static final String SUCCESS_MSG = "请求成功";
" +
                "    public static final int EXCEPTION_CODE = 404;
" +
                "    public static final String EXCEPTION_MSG = "请求处理异常";
" +
                "    public static final int ERROR_CODE = 500;
" +
                "    public static final String ERROR_MSG = "请求方式有误,请检查 GET/POST";
" +
                "    public static final int NOT_URL_CODE = 501;
" +
                "    public static final String NOT_URL_MSG = "请求路径不存在";
" +
                "    public static final int INSUFFICIENT_AUTHORITY_CODE = 502;
" +
                "    public static final String INSUFFICIENT_AUTHORITY_MSG = "权限不足";
" +
                "    public static final int LOGON_EXPIRATION_CODE = 20011;
" +
                "    public static final String LOGON_EXPIRATION_MSG = "登陆已过期";*/
" +
                "
" +
                "    //状态码
" +
                "    int code;
" +
                "    //数据
" +
                "    Object data;
" +
                "    //消息提示
" +
                "    String message;
" +
                "    //数量
" +
                "    int count;
" +
                "
" +
                "
" +
                "    public int getCount() {
" +
                "        return count;
" +
                "    }
" +
                "
" +
                "
" +
                "    public void setCount(int count) {
" +
                "        this.count = count;
" +
                "    }
" +
                "
" +
                "
" +
                "    public Result() {
" +
                "    }
" +
                "
" +
                "    public Result(int code, String message) {
" +
                "        this.code = code;
" +
                "        this.message = message;
" +
                "    }
" +
                "
" +
                "    public Result(int code, String message, Object data) {
" +
                "        this.code = code;
" +
                "        this.message = message;
" +
                "        this.data = data;
" +
                "    }
" +
                "    public Result(int code, String message, Object data, int count) {
" +
                "        this.code = code;
" +
                "        this.data = data;
" +
                "        this.message = message;
" +
                "        this.count = count;
" +
                "    }
" +
                "
" +
                "    public int getCode() {
" +
                "        return code;
" +
                "    }
" +
                "
" +
                "    public void setCode(int code) {
" +
                "        this.code = code;
" +
                "    }
" +
                "
" +
                "    public Object getData() {
" +
                "        return data;
" +
                "    }
" +
                "
" +
                "    public void setData(Object data) {
" +
                "        this.data = data;
" +
                "    }
" +
                "
" +
                "    public String getMessage() {
" +
                "        return message;
" +
                "    }
" +
                "
" +
                "    public void setMessage(String message) {
" +
                "        this.message = message;
" +
                "    }
" +
                "
" +
                "
" +
                "    /**
" +
                "     * code:200
" +
                "     * msg:请求成功
" +
                "     *
" +
                "     * @return
" +
                "     */
" +
                "    public static Result success() {
" +
                "        return new Result(200, "true");
" +
                "    }
" +
                "
" +
                "
" +
                "    /**
" +
                "     * code:201
" +
                "     * msg:请求失败
" +
                "     *
" +
                "     * @return
" +
                "     */
" +
                "    public static Result error() {
" +
                "        return new Result(201, "false");
" +
                "    }
" +
                "    /**
" +
                "     * code:201
" +
                "     * msg:请求失败
" +
                "     *
" +
                "     * @return
" +
                "     */
" +
                "    public static Result error(String message) {
" +
                "        return new Result(201, message);
" +
                "    }
" +
                "
" +
                "    /**
" +
                "     * successMessage
" +
                "     * 正常返回,携带消息
" +
                "     * code:200
" +
                "     *
" +
                "     * @param message 消息
" +
                "     *                data:null
" +
                "     *                count:0
" +
                "     * @return
" +
                "     */
" +
                "    public static Result successMessage(String message) {
" +
                "        return new Result(200, message);
" +
                "    }
" +
                "
" +
                "    /**
" +
                "     * success
" +
                "     * 成功方法 带数据返回
" +
                "     * code:200
" +
                "     *
" +
                "     * @param data  数据
" +
                "     * @param count 总数
" +
                "     * @return
" +
                "     */
" +
                "    public static Result success(Object data, int count) {
" +
                "        return new Result(200, "true", data, count);
" +
                "    }
" +
                "
" +
                "    /**
" +
                "     * success
" +
                "     * 成功方法 带数据返回
" +
                "     * code:200
" +
                "     * message: success
" +
                "     *
" +
                "     * @param data 数据
" +
                "     *             count :0
" +
                "     * @return
" +
                "     */
" +
                "    public static Result success(Object data) {
" +
                "        return new Result(200, "true", data, 0);
" +
                "    }
" +
                "
" +
                "    /**
" +
                "     * error
" +
                "     * data:null
" +
                "     * count:0
" +
                "     *
" +
                "     * @param code    错误编码
" +
                "     * @param message 错误信息
" +
                "     * @return
" +
                "     */
" +
                "    public static Result error(int code, String message) {
" +
                "        return new Result(code, message);
" +
                "    }
" +
                "
" +
                "}
";
        return controller;
    }

    /**
     * 开始创建
     *
     * @param tableName 数据库表
     */
    static void createStart(String tableName) {
        //创建Dao
        //createFile(new File(srcPackage + "dao\" + tableName + "Mapper.java"), createDao(tableName));
        //创建Service
        System.out.println("创建Service");
        createFile(new File(srcPackage + "service\" + tableName + "Service.java"), createService(tableName));
        //创建ServiceImpl
        System.out.println("创建ServiceImpl");
        createFile(new File(srcPackage + "service\impl\" + tableName + "ServiceImpl.java"), createServiceImpl(tableName));
        //创建Controller
        System.out.println("创建Controller");
        createFile(new File(srcPackage + "controller\" + tableName + "Controller.java"), createController(tableName));
    }


}
View Code

注意:修改自己项目根目录的包名 以及使用数据库的使用账号密码和驱动等等

 下一步启动Main()方法:

 第一次配置成功后不要直接启动Main()方法,要去pom里面import相关的包再启动:输入2

第二次配置完成后,打开右边的Maven执行mybatis-generator:generate

 

执行完成后会有dao和实体出现

最后我们去配置Tomcat 完成后就直接可以编写代码

我们就搭建好了一个 ssm 的maven项目

原文地址:https://www.cnblogs.com/chen1005/p/10528042.html