Blog site based on SpringBoot+Vue (starting with 0) --- 5th day

Keywords: Java Spring Boot Vue.js

Child's Bay Sunset

Build Project

 

Create Parent Project

I'm using a mirror of aliyun here. The spring official I can't really load it, so it's basically aliyun.   Then use jdk8

Since there is a reverse engineering and our business logic module project, we just need to check the Spring Boot in the diagram to build a parent project.   Devtools will do, and other dependencies can be built before they are added. Version here I am now 2.3.7.REKEASE

  After this next, just find a folder to put it in, preferably in English.

After the project is built, delete everything and leave a pom file. This project is mainly used for pom dependency management, so nothing else will be used.

We don't need dependencies or builds, so we delete them. (Select Delete)

Then add the packaing and change the parent tag. Otherwise, the later dependencies can't be found, which I don't understand, I can only think about working properly by myself.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.hotin</groupId>
    <artifactId>blog</artifactId>
    <version>1.0.0</version>
    <modules>
        <module>blog-server</module>
    </modules>
    <name>blog</name>
    <packaging>pom</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/>
    </parent>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
</project>

Create a blog-server subproject

Create Aggregate Project

Make sure the parent item is selected so that the child can be associated. If not, tag the pom file with parent

  Modify pom file

  Add Dependency

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>blog</artifactId>
        <groupId>com.hotin</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>blog-server</artifactId>
    <name>blog-server</name>
    <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>
    </properties>

    <dependencies>
        <!--web rely on-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--lombok rely on-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--mysql rely on-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mybatis-plus rely on-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <!-- swagger2 rely on -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <!-- Swagger Third party ui rely on -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
    </dependencies>

</project>

Then delete the test directory, use no test classes, delete the App classes under java, override them, and add a server package to the path

  Next up is the resources directory

Notice here that if the resources flag doesn't appear, you need to convert it, and I do, so I don't need to use Mark anymore.

 

Then create a config directory, create a new File - -- application.yml, the application.yml configuration file has a clear main hierarchy, you can also use application.properties. Personal preferences.

  application.yml Configuration File

server:
  # port
  port: 8081
spring:
  # Data Source Configuration
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/vueblog?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: root
    password: 333
    hikari:
      # Connection pool name
      pool-name: DateHikariCP
      # Minimum number of idle connections
      minimum-idle: 5
      # Maximum time to live for idle connections, default 600000 (10 minutes)
      idle-timeout: 180000
      # Maximum number of connections, default 10
      maximum-pool-size: 10
      # Autocommit of connections returned from connection pool
      auto-commit: true
      # Maximum lifetime of connection, 0 means permanent survival, default 1800000 (30 minutes)
      max-lifetime: 1800000
      # Connection timeout, default 30000 (30 seconds)
      connection-timeout: 30000
      # Query statements that test whether a connection is available
      connection-test-query: SELECT 1
  # Redis Configuration
  redis:
    # Connection timeout
    timeout: 10000ms
    # Redis Server Address
    host: 192.168.70.128
    # Redis Server Port
    port: 6379
    # Choose which library, default 0 Library
    database: 0
    lettuce:
      pool:
        max-active: 1024 # Maximum number of connections, default 8
        max-wait: 10000ms  # Maximum connection blocking wait time, in milliseconds, default -1
        max-idle: 200  # Maximum idle connection, default 8
        min-idle: 5   # Minimum idle connection, default 0
    password: test123
# Mybatis-plus Configuration
mybatis-plus:
  # Configure Mapper Mapping File
  mapper-locations: classpath*:/mapper/*Mapper.xml
  # Configure MyBatis data return type alias (default alias is class name)
  type-aliases-package: com.hotin.server.pojo
  configuration:
  # Automatic hump naming
    map-underscore-to-camel-case: false
## Mybatis SQL Printing (package for method interface, not Mapper.xml)
logging:
  level:
    root:
  com.Htsys.server.mapper: debug

jwt:
  # JWT Stored Request Header
  tokenHeader: Authorization
  # Key used for JWT encryption and decryption
  secret: blog-secret
  # JWT expiration time (60*60*24)
  expiration: 604800
  # Get started in JWT load
  tokenHead: Bearer

Then create a mapper directory under resources to store mapper files

#Configure Mapper Mapping File
mapper-locations: classpath*:/mapper/*Mapper.xml

 

Then build a pojo package

All module building packages

 

  Override our boot class VueBlogApplication

package com.hotin.server;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Startup Class
 *
 * @author  :hotin
 * @date    :2021/11/20 22:13
 */

@SpringBootApplication
// Mapper Scanner
@MapperScan("com.hotin.server.mapper")
public class VueBlogApplication {
    public static void main(String[] args) {
        SpringApplication.run(VueBlogApplication.class, args);
    }
}

reverse engineering

Code generator

AutoGenerator is the code generator for MyBatis-Plus. AutoGenerator can quickly generate code for Entity, Mapper, Mapper XML, Service, Controller and other modules, which greatly improves development efficiency.

What can AutoGenerator do?

For single forms, it is almost an all-round tool, greatly improving development efficiency, allowing developers to focus more on business logic
Implementation.

Create a blog-generator project

As in previous build aggregation projects

Then delete anything you don't use, rewrite the pom file, and add dependencies.

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>blog</artifactId>
    <groupId>com.hotin</groupId>
    <version>1.0.0</version>
  </parent>
  <artifactId>blog-generator</artifactId>
  <version>1.0.0</version>

  <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>
  </properties>

  <dependencies>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mybatis-plus rely on-->
        <dependency>
          <groupId>com.baomidou</groupId>
          <artifactId>mybatis-plus-boot-starter</artifactId>
          <version>3.3.1.tmp</version>
        </dependency>
        <!--mybatis-plus Code Generator Dependency-->
        <dependency>
          <groupId>com.baomidou</groupId>
          <artifactId>mybatis-plus-generator</artifactId>
          <version>3.3.1.tmp</version>
        </dependency>
        <!--freemarker rely on-->
        <dependency>
          <groupId>org.freemarker</groupId>
          <artifactId>freemarker</artifactId>
        </dependency>
        <!--mysql rely on-->
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <scope>runtime</scope>
        </dependency>
  </dependencies>


</project>

Create CodeGenerator Class to Launch Code Generator

The contents of the change are clear as database name, project name and package name. You can eat them by referring to the documents on the official website.

package com.hotin.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Execute main method console input module table name carriage return to automatically generate corresponding project directory
 *
 * @author hotin
 * @since 1.0.0
 */
public class CodeGenerator {
    /**
     * <p>
     * Read console content
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("Please enter" + tip + ": ");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("Please enter correct" + tip + "!");
    }

    public static void main(String[] args) {
        // Code generator
        AutoGenerator mpg = new AutoGenerator();
        // Global Configuration
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/blog-generator/src/main/java");
        //author
        gc.setAuthor("hotin");
        //Open Output Directory
        gc.setOpen(false);
        //xml Open BaseResultMap
        gc.setBaseResultMap(true);
        //xml opens BaseColumnList
        gc.setBaseColumnList(true);
        // Entity Attribute Swagger2 Comment
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);
        // Data Source Configuration
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/vueblog?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia" +
                "/Shanghai");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("333");
        mpg.setDataSource(dsc);
        // Package Configuration
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.hotin.server")
                .setEntity("pojo")
                .setMapper("mapper")
                .setService("service")
                .setServiceImpl("service.impl")
                .setController("controller");
        mpg.setPackageInfo(pc);
        // Custom Configuration
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        // If the template engine is freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // If the template engine is velocity
        // String templatePath = "/templates/mapper.xml.vm";
        // Custom Output Configuration
        List<FileOutConfig> focList = new ArrayList<>();
        // Custom configuration will be output first
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo){
                // Custom output file name, if your Entity has prefix and suffix set, note here that the name of xml will change with it!!
                return projectPath + "/blog-generator/src/main/resources/mapper/"
                        + tableInfo.getEntityName() + "Mapper"
                        + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // Configuration Template
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        // Policy Configuration
        StrategyConfig strategy = new StrategyConfig();
        //Naming strategies for database tables mapped to entities
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //Naming strategies for mapping database table fields to entities
        strategy.setColumnNaming(NamingStrategy.no_change);
        //lombok model
        strategy.setEntityLombokModel(true);
        //Generate @RestController controller
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("Table name, separated by multiple English commas").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        //Table Prefix
        strategy.setTablePrefix("t_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
implement

Result

 

Copy and paste the generated pojo, service, controller, mapper into the package corresponding to java on the blog-server project, and then copy and paste the generated mapper into the package corresponding to resources on the blog-server project.

 

Check that the class you are reporting is red, that you have written the package name correctly, and that the configuration file is written correctly without major problems.

Start learning to write Shiro login framework tomorrow, oh, in fact, I did not learn, I just learned Spring Security, want to change, know more, so I changed shiro.

Experience

Today, although it is Saturday, we should write a little more, but it takes a lot of thought to find out how the reverse should be used, and Saturday is also a day of meetings. I wrote these during the afternoon and evening. It is written out very quickly and I need to sort out the article to see if what I said is correct. I think there will still be a lot of problems. You see can help point out, if there is any infringement, please contact to delete.

Posted by holiks on Sat, 20 Nov 2021 14:22:55 -0800