7月份应用知识点回顾总结

7月份应用知识点回顾总结

1. SpringBoot+SpringMVC+Mybatis-Plus 系统整合搭建

  1. 导包(pom.xml),需要的有spring-boot-starter-webmybatis-plus-boot-starter这两个已经足够了。因为springboot起步依赖的原因,其他包会自动导入的。然后因为需要连接数据库,所以还需要mysql-connector-java如果是其他数据库就用其他数据库对应的包
  2. 添加配置文件
# 端口号
server.port=9002
# 项目名字
spring.application.name=centanet-news
# 环境设置dev test prod
spring.profiles.active=dev
# 数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
## 测试库
spring.datasource.url=jdbc:mysql://10.4.18.101:3306/test_centanewsinfo_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=TestWeb_CPost
spring.datasource.password=P@ssW()2020T5T15
# 日志
logging.level.root=info
logging.file.name=news_java-dev.log
# mybatis-plus 设置
# mybatis 日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 映射文件
mybatis-plus.mapper-locations=classpath:com/centanet/news/mapper/xml/*.xml
  1. 写代码:启动类(一个包含main函数的类),entity(实体),service(服务)controller(接口),mapper(数据关系映射),可能还需要 config(配置类)

2. SpringMVC controller参数绑定

目前在系统里使用的有两种:一种是通过@RequestParam(value = "ignores",required = false)String ignores进行绑定,另外一种就是通过bean进行自动绑定(TrackLogVO trackLogVO)

两种其实差不多,前面一种适合参数比较少的时候,后面一种适合参数多的时候

3. Mybatis一对多查询

这个就需要用到mybatis的参数绑定和对线关系映射。主要利用的collection(一对多),association(一对一)

<resultMap id="NewsContentDTOMap" type="com.centanet.news.entity.dto.NewsContentDTO">
        <id column="id" property="id"/>
        <result column="title" property="title"/>
        <result column="pubdate" property="pubdate"/>
        <result column="body" property="body"/>
        <result column="redirecturl" property="redirecturl"/>
        <result column="source" property="source"/>
        <result column="writer" property="writer"/>
        <result column="description" property="description"/>
        <result column="typename" property="typename"/>
        <result column="typeid" property="typeid"/>
        <result column="litpic" property="litpic"/>
        <result column="houseAgent" property="houseAgent"/>
        <result column="flag" property="flag"/>
        <collection property="newsRelated" ofType="com.centanet.news.entity.DedeNewsRelated">
            <id column="did" property="id"/>
            <result column="newsid" property="newsId"/>
            <result column="oid" property="oId"/>
            <result column="otype" property="oType"/>
            <result column="dpubDate" property="pubDate"/>
        </collection>
    </resultMap>
<select id="getNewsContentById" parameterType="Integer" resultMap="NewsContentDTOMap">
        select
        a.id,a.title,a.pubdate,c.body,c.redirecturl,a.source,a.writer,a.description,b.typename,a.typeid,a.litpic,b.houseAgent,a.flag,
        d.id as 'did',d.newsid,d.oid,d.otype,d.pubdate as 'dpubDate'
        from dede_archives a
        INNER JOIN dede_addonarticle c on a.id = c.aid
        INNER JOIN dede_arctype b on b.id = a.typeid
        left JOIN dede_newsrelated d on d.newsid = a.id
        where a.id = #{id}
    </select>

4. controller请求链接不区分大小写

controller里面 域名/api/getUserID/05 这种链接是区分大小的,但是实际我们输入BaiDU.com也是能找到百度的,这就需要我们请求连接不区分大小写

添加webmvc配置

import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Author: wbdengtt
 * @Date: 2020/7/9 8:49
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 忽略URL大小写
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        pathMatcher.setCaseSensitive(false);
        configurer.setPathMatcher(pathMatcher);
    }
}

5. controller参数不区分大小写

理论上可以配置,但是我实际上没有找到怎么做。我是通过获取HttpServletRequest里面的参数,然后将key全部转化成小写来实现的

参考代码(这种方式只适合get接口):

/**
     * 获取连接里面的的参数
     */
    public static Map<String,String> getParameterMap(HttpServletRequest request) {
        Enumeration<String> keys = request.getParameterNames();
        // 存放经过处理后的参数 :将K小写
        Map<String,String> targetMap = new HashMap<>(16);
        String key = null;
        while (keys.hasMoreElements()) {
            key = keys.nextElement();
            targetMap.put(key.toLowerCase(),request.getParameter(key));
        }
        return targetMap;

    }

6. Jsoup爬虫爬取公众号资讯

  1. 导包
<!--jsoup 爬虫相关,用来爬取网页数据-->
        <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.13.1</version>
        </dependency>
  1. 相关代码(链接网页,获取document对象,然后对document对象进行操作)
package com.centanet.news.helpper.jsoup;

import com.centanet.news.handler.NewsException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * @author 邓天天
 * @date 2020/7/12 15:21
 * 工具类,不允许实例化
 */
public class JsoupHelper {
    private JsoupHelper(){}
    /**
     * 通过URL获取原始网页的DOC
     * @param url 需要抓取的网页
     * @return 返回一个document对象
     */
    public static Document getDocumentByUrl(String url) {
        try {
            return Jsoup.connect(url).get();
        } catch (IllegalArgumentException | IOException e) {
            throw new NewsException(410,"该URL: "+url+" 无法爬取。请检查URL", e);
        }
    }
    public static String getFirstImage(Document document) {
        Elements imgs = document.select("meta[property=\"og:image\"]");
        if (!imgs.isEmpty()) {
            return imgs.get(0).attr("content");
        }
        return null;
    }
    /**
     * 将DOC初步处理
     * 返回的DOC不包含 Script和meta元素
     * 同时将 visibility 的hiden属性换成visible
     * @return 返回一个粗糙的doc文件
     */
    public static Document getDocumentWithoutScriptAndMeta(Document doc) {
        // 移除script元素
        doc.getElementsByTag("script").remove();
        // 移除meta元素
        doc.getElementsByTag("meta").remove();
        // 将visibility 为隐藏的找出来,并且将其设置成visible
        Elements elements = doc.select("[style=\"visibility: hidden;\"]");
        elements.attr("style","visibility: visible;");
        return doc;
    }
}

7. @JsonProperty的使用

@JsonProperty(“publicDate”)

用来指定序列化后该字段的显示的名字

8. 多数据源配置

需要导相关jar包(pom.xml)dynamic-datasource-spring-boot-starter

<dependency>
         <groupId>com.baomidou</groupId>
         <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
         <version>3.1.1</version>
     </dependency>

然后配置数据库的数据源application.properties

# 多数据库配置
# 集团库
spring.datasource.dynamic.primary=jt
spring.datasource.dynamic.strict=false
spring.datasource.dynamic.datasource.jt.url=jdbc:sqlserver://10.4.18.128\\dgsql2014;DatabaseName=CentaMonitor
spring.datasource.dynamic.datasource.jt.username=temp
spring.datasource.dynamic.datasource.jt.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.dynamic.datasource.jt.password=P@ssw0r
# 深圳库
spring.datasource.dynamic.datasource.sz.url=jdbc:sqlserver://10.6.252.24\\SZSQLRW01;DatabaseName=CentaSysLog
spring.datasource.dynamic.datasource.sz.username=temp
spring.datasource.dynamic.datasource.sz.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.dynamic.datasource.sz.password=P@ssw0r

最后是应用:在service上使用@DS(“SZ”)来指定深圳数据库。如果没有指定,默认使用primary指定的数据库

9. JsonDiff

首先导包

<!-- https://mvnrepository.com/artifact/com.flipkart.zjsonpatch/zjsonpatch -->
        <dependency>
            <groupId>com.flipkart.zjsonpatch</groupId>
            <artifactId>zjsonpatch</artifactId>
            <version>0.4.10</version>
        </dependency>

然后直接使用JsonDiff.asJson(source,target).toString();函数

public static String jsonDiffWithIgnore(String oldJson, String newJson,String[] ignores) throws JsonProcessingException {
        if (ignores !=null && ignores.length!=0){
            oldJson = modifyJson(oldJson,ignores);
            newJson = modifyJson(newJson,ignores);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode source = objectMapper.readTree(oldJson);
        JsonNode target = objectMapper.readTree(newJson);
        return JsonDiff.asJson(source,target).toString();
    }

10. 面向对象,继承多态封装,抽象与具体

11. 工厂模式,单例模式,构建者模式,代理模式

12. logback日志

https://blog.csdn.net/Inke88/article/details/75007649

13. Maven相关知识点

https://blog.csdn.net/m0_37628958/article/details/107575760

14. IO流相关

InputStream 输入流,将数据读取到程序

OutputStream输出流,将数据写到磁盘或网络传输

15. 多线程和线程池

创建线程的三种方式:①继承Thread ②重写Runnable接口 ③重写Callable接口

线程池的原理:接到任务后,先判断工作的线程是是否小于核心线程数,是则创建一个线程,否则将其添加的工作队列。判断工作队列是否已满,没有则添加到工作队列。满了则判断正在工作的线程是是否小于最大线程数,是新建线程,否将任务讲给任务处理器(一般就是直接丢掉)

package com.mobile.api.java.tool.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.mobile.api.java.tool.entity.dto.JsonDTO;
import com.mobile.api.java.tool.entity.dto.TrackLogDTO;
import com.mobile.api.java.tool.entity.dto.TrackLogResultDTO;
import com.mobile.api.java.tool.helper.HttpHelper;
import com.mobile.api.java.tool.helper.JsonHelper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author: wbdengtt
 * @Date: 2020/7/24 9:57
 */
@Data
@Slf4j
public class ThreadPoolHelper {

    /**
     * 用来接收结果
     */
    private ConcurrentLinkedQueue<TrackLogResultDTO> resultQueue;

    /**
     * 接收参数
     */
    private ConcurrentLinkedQueue<TrackLogDTO> paramQueue;

    /**
     * 忽略字段
     */
    private String[] ignores;

    private CountDownLatch countdown;

    /**
     * 初始化,将logList转化为paramQueue
     * @param trackLogDTOList 参数
     * @param ignores 忽略字段
     */
    public void init(List<TrackLogDTO> trackLogDTOList, String[] ignores){
        resultQueue = new ConcurrentLinkedQueue<>();
        paramQueue = new ConcurrentLinkedQueue<>();
        // 避免傻乎乎的让CPU空转来等待宣传允许完毕
        countdown = new CountDownLatch(trackLogDTOList.size());
        paramQueue.addAll(trackLogDTOList);
        this.ignores = ignores;
    }

    /**
     * 执行数据对比,同时可以指定需要多少个线程来处理
     * @param nThreads 参数的线程数目
     */
    public void doDiff(int nThreads) {

        ExecutorService executorPool = ThreadPoolHelper.getThreadPool();
        for (int i = 0; i < nThreads; i++){
            ThreadRunnable threadRunnable = new ThreadRunnable();
            executorPool.execute(threadRunnable);
        }
        try {
            countdown.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("await失败,请检查");
        }
        log.info("线程执行结束");
    }

    class ThreadRunnable implements Runnable{

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
            TrackLogDTO trackLogDTO;
            JsonDTO jsonDTO;
            线程工作内容,,,省略
    }

    public static ExecutorService getThreadPool() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
        return new ThreadPoolExecutor(20,20,0L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(),threadFactory);
    }

}

16. 序列化和反序列化

序列化就是将对象转成可存储到磁盘,或者可以进行网络传输的状态。

反序列化就是将存储的可存储和传输状态变成可使用的对象状态。

json是序列化的一种,和序列化的区别是json只包含域

序列化和反序列化会破坏单例

生成对象的方式:克隆,反射,new,反序列化

17. sonar集成使用

https://blog.csdn.net/m0_37628958/article/details/107380739

18. Swagger2配置

用来生成接口描述的

导包

<!--swagger-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>${swagger.version}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>${swagger.version}</version>
            </dependency>

添加配置类

package com.centanet.news.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
 * @Author: wbdengtt
 * @Date: 2020/7/6 9:53
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    public static final String SWAGGER2_SCAN_BASE_PACKAGE = "com.centanet.news.controller";
    public static final String VERSION = "1.0.0";

    @Bean
    public Docket createResetApi(){

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(webApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER2_SCAN_BASE_PACKAGE))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo webApiInfo(){
        // 设置标题,文档描述,版本
        return new ApiInfoBuilder()
                .title("中原资讯系统")
                .description("中原咨询系统接口")
                .version(VERSION)
                .contact(new Contact("邓天天","www.news.centanet.com","[email protected]"))
                .build();
    }
}

上面的配置已经可以使用了。还可以通过注解添加接口和参数描述

 @ApiOperation(value = "获取文章详情",notes = "获取文章详情")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "cityen",value = "城市", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "platform",value = "平台", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "newsid",value = "文章id", paramType = "query", dataType = "Integer")
    })

19. Mybatis查询参数映射

返回值映射

<resultMap id="TrackLogMap" type="com.mobile.api.java.tool.entity.TrackLog">
        <id column="Id" property="id"/>
        <result column="FullName" property="fullName"/>
        <result column="MethodName" property="methodName"/>
        <result column="Message" property="message"/>
    </resultMap>
    <select id="getTopTenTrackLog" resultMap="TrackLogMap" parameterType="com.mobile.api.java.tool.entity.vo.TrackLogVO">
        SELECT top 10 Id, FullName,MethodName,Message
        FROM [dbo].[TrackLog]
        WHERE Message like 'http://mobileapi.centanet.com%'
        and FullName like 'MobileApi.CentaNet.Mobile.Model.Request%'
        <if test="methodName != null">
            and MethodName like concat('%',#{methodName},'%')
        </if>
        <if test="fullName != null">
            and FullName like concat('%',#{fullName},'%')
        </if>
        ORDER BY Id desc
    </select>

入参映射:https://blog.csdn.net/qq_29410905/article/details/80043180

① 上面这种,通过bean进行映射。

②通过下标

③通过@param注解

④通过list集合

⑤通过map集合

其中①和③是比较常见的

20. Mybatis条件查询

<select id="listTopHundredTrackLog" resultMap="TrackLogMap" parameterType="com.mobile.api.java.tool.entity.vo.TrackLogVO">
        SELECT top 300 Id, FullName,MethodName,Message
        FROM [dbo].[TrackLog]
        WHERE Message like 'http://mobileapi.centanet.com%'
        and FullName like 'MobileApi.CentaNet.Mobile.Model.Request%'
        <if test="methodName != null">
            and MethodName like concat('%',#{methodName},'%')
        </if>
        <if test="fullName != null">
            and FullName like concat('%',#{fullName},'%')
        </if>
        <if test="startDate != null">
            and RowDate >= #{startDate}
        </if>
        <if test="endDate != null">
            and RowDate &lt;= #{endDate}
        </if>
        ORDER BY Id desc
    </select>

还有一种方式是利用 这个可以避免多余and的情况

21. Mybatis分页

mybatis本身并没有分页,需要利用自己的sql来实现。其实就是利用查询语句的limit 0,10(从0条开始取10条)

22. Maven项目的打包发布

maven项目要遵守maven的目录结构,同时需要在build里面添加maven插件,以及将需要的文件都包含进去

maven命令:mvn clean 清楚缓存 mvn package 打包,默认是是jar包,也可以通过pom进行指定

 <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>com/centanet/news/mapper/xml/*.xml</include>
                </includes>
            </resource>
            <!--我感觉打包没有把我的属性文件包含进去,手动包含设置下-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>*.properties</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

23. 爬取的文章无法显示问题的解决方案

有可能是有个<style 的visibility属性为hidden 导致的。将其改成 visibility。

// 将visibility 为隐藏的找出来,并且将其设置成visible
        Elements elements = doc.select("[style=\"visibility: hidden;\"]");
        elements.attr("style","visibility: visible;");

24. 分环境打包部署

环境有dev,test,prod

需要在配置文件 application.properties指定 spring.profiles.active = dev

然后再jar允许时指定 java -jar XXXX.jar --spring.profiles.active=test

注意maven打包时需要包换properties文件,否则可能找不到文件导致运行失败

25. httpclient获取网络接口结果

导包(因为起步依赖制定了对应的版本,所以我这里不需要)

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

获取远程接口结果工具类

package com.mobile.api.java.tool.helper;

import com.mobile.api.java.tool.entity.dto.JsonDTO;
import com.mobile.api.java.tool.entity.dto.TrackLogDTO;
import com.mobile.api.java.tool.entity.dto.UrlDTO;
import org.apache.http.HttpEntity;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.lang.NonNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author: wbdengtt
 * @Date: 2020/7/21 13:12
 */
public class HttpHelper {
    private HttpHelper() {}
	// 结果处理器 (这是一个lambda表达式)
    private static final ResponseHandler<String> RESPONSE_HANDLER = response -> {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    };

    public static JsonDTO getNetAndJavaApiResponse(TrackLogDTO trackLogDTO) throws IOException {
        JsonDTO jsonDTO = new JsonDTO();
        jsonDTO.setNetJson(getStringResultByUrl(trackLogDTO.getNetUrl()));
        jsonDTO.setJavaJson(getStringResultByUrl(trackLogDTO.getJavaUrl()));
        return jsonDTO;
    }

    /**
     * 传统方式通过URL获取接口里面的结果
     * @param url 路径
     * @return 返回查询的结果
     */
    public static String getStringResultByUrl(@NonNull String url) throws IOException {
        URL myUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = in.readLine())!=null){
            sb.append(line);
        }
        in.close();
        return sb.toString();
    }

	// httpclient方式获取get接口结果
    public static String getStringResult(CloseableHttpClient httpClient, String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        return httpClient.execute(httpGet,RESPONSE_HANDLER);
    }
    // httpclient方式获取post结果
    public static String postStringResult(CloseableHttpClient httpClient, String url) throws IOException {
        String trueUrl = url.substring(0,url.indexOf(","));
        String param = url.substring(url.indexOf("{"));
        HttpPost httpPost = new HttpPost(trueUrl);
        httpPost.setHeader("Accept","application/json");
        httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
        StringEntity entity = new StringEntity(param,"utf-8");
        httpPost.setEntity(entity);
        return httpClient.execute(httpPost,RESPONSE_HANDLER);
    }


    public static JsonDTO getNewNetAndJavaApiResponse(UrlDTO urlDTO, CloseableHttpClient httpClient) throws IOException {
        JsonDTO jsonDTO = new JsonDTO();
        String isPost = "POST参数";
        if (urlDTO.getNetUrl().contains(isPost)) {
            jsonDTO.setNetJson(postStringResult(httpClient,urlDTO.getNetUrl()));
            jsonDTO.setJavaJson(postStringResult(httpClient,urlDTO.getJavaUrl()));
            return jsonDTO;
        }
        jsonDTO.setNetJson(getStringResult(httpClient,urlDTO.getNetUrl()));
        jsonDTO.setJavaJson(getStringResult(httpClient,urlDTO.getJavaUrl()));
        return jsonDTO;
    }


}

26. mybatis-plus自动生成代码配置

  1. 导包。在原先SSM配置的包上额外需要mybatis-plus-generatorvelocity-engine-core
<!--代码生成器-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>${mybatis-plus.version}</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity-engine-core -->
            <!--velocity 模板引擎,生成mybatis-plus代码生成器需要-->
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
                <version>${velocity.version}</version>
            </dependency>
  1. 生成器代码
package helpper;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.jupiter.api.Test;

/**
 *  @Author: wbdengtt
 *  @Date: 2020/7/6 9:25
 */
public class CodeGenerator {
	@Test
    public void run() {

        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("邓天天");
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(false); //重新生成时文件是否覆盖
        // gc.setServiceName("%sService");    //去掉Service接口的首字母I
        gc.setIdType(IdType.AUTO); //主键策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//开启Swagger2模式

        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://10.4.18.101:3306/test_centanewsinfo_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("TestWeb_CPost");
        dsc.setPassword("P@ssW()2020T5T15");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("news"); //模块名
        pc.setParent("com.centanet");
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        //修改表名字。对应生成哪个
        strategy.setInclude("dede_viewhistory");
        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作

        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);


        // 6、执行
        mpg.execute();
    }
}

  1. 执行生成器,就可以自动生成 controller,service,mapper, entity等模板代码

猜你喜欢

转载自blog.csdn.net/m0_37628958/article/details/107762953