newProJava框架 Java开发工具

spring boot 集成TKmpaper生成复杂语句 逆向工

2020-02-08  本文已影响0人  刘小刀tina

1. pom.xml


    <dependencies>

        <!--springboot web启动依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--加入lombok,注解生成Getter、Setter-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!--mysql 数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>


        <!-- servlet 依赖. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>

        <!-- JSTL-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!--通用Mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.5</version>
        </dependency>


        <!--jdbc驱动-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <!--使用阿里巴巴的druid数据源,有利于监控sql的执行情况-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--添加单元测试-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.5.2</version>
        </dependency>


        <!--添加swagger2依赖的jar包-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>


        <!--引入thymeaf模版-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.11.RELEASE</version>
        </dependency>

        <!--后端JSR303校验依赖包-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.9.Final</version>
        </dependency>

        <!--spring Boot测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.3.RELEASE</version>
            <scope>compile</scope>
        </dependency>


    </dependencies>

    <!-- 构建节点. -->
    <build>
        <plugins>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <!-- 是否覆盖,true表示会替换生成的JAVA文件,false则不覆盖 -->
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                    <configurationFile>
                        src/main/resources/generatorConfig.xml
                    </configurationFile>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>4.0.3</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

2. 配置文件

application.properties


###datasource
spring.datasource.url = jdbc:mysql://152.136.27.48:3306/d_yoyo?characterEncoding=utf8
#  jdbc:mysql://152.136.27.48:3306/d_yoyo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

#SpringBoot项目解决全局响应返回中文乱码问题
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

============================================================
application.yml

#指定端口号
server:
  port: 8002

##配置mmysql数据源
spring:
  datasource:

    #配置数据连接池
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: true
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500



#配置MYBATIS
mybatis:
  #指定映射文件的位置
  mapper-locations: classpath:mapper/*.xml
  #指定实体类包的位置
  type-aliases-package: com.tina.gmalluser.product.entity
  configuration:
    map-underscore-to-camel-case: true #下划线转驼峰


#配置分页插件
pagehelper:
  helperDialect: mysql
  reasonable: true #跳转分页合理化参数
  supportMethodsArguments: true
  params: count=countSql

#打印sql
logging:
  level:
    com.tina.gmalluser.product.mapper : debug
============================================================

generatorConfig.xml

<?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>
    <!--系统全局配置文件-->
    <!--指定数据源的位置-->
    <properties resource="application.properties" />

    <!-- 数据库驱动:mysql数据库驱动包路径 -->
    <classPathEntry location="/Users/lvxiaokai/Desktop/tina/apache-maven-3.6.3/repository/mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar"/>

    <!--context:代码生成规则配置的上下文
            id:标识
            targetRuntime: MyBatis3Simple 只会生成基本的CRUD操作-->
    <context id="Mysql" targetRuntime="MyBatis3Simple"  defaultModelType="flat">

        <!-- 生成的Java文件的编码 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 格式化java代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <!-- beginningDelimiter和endingDelimiter:
        指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
            <property name="caseSensitive" value="true"/>
            <!--集成lombok-->
            <property name="lombok" value="Getter,Setter,ToString"/>
        </plugin>

        <!-- 生成的实体Bean,将实现Serializable -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>

        <!--commentGenerator:注释生成策略-->
        <commentGenerator>
            <!--suppressDate:是否阻止时间戳生成--><!-- 如果生成日期,会造成即使修改一个字段,整个实体类所有属性都会发生变化,不利于版本控制,所以设置为true -->
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="${spring.datasource.driverClassName}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}"
        >
        </jdbcConnection>

        <!-- 类型转换 -->
        <javaTypeResolver >
            <!-- 是否使用bigDecimal,
                false: 把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer(默认)
                true:  把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal
            -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--domain生成策略;targetPackage:生成到哪个包下面,targetProject:生成到哪个项目目录下面-->
        <javaModelGenerator targetPackage="com.tina.gmalluser.product.entity" targetProject="src/main/java">
            <!-- 默认false 是否允许子包 -->
            <property name="enableSubPackages" value="true" />
            <!-- 默认false 是否对model添加 构造函数 -->
            <property name="constructorBased" value="false"/>
            <!-- 默认false 建立的Model对象是否不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="true"/>
            <!--表示是否修剪字符串(去掉空格--><!-- 默认false 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--sqlMapGenerator:映射文件生成策略
              targetPackage:生成到哪个包下面,targetProject:生成到哪个项目目录下面
       -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--mapper接口生成策略
                   type:ANNOTATEDMAPPER:注解的形式
                        XMLMAPPER:xml映射的形式-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.tina.gmalluser.product.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>


        <!-- 指定要生成代码的表  domainObjectName:设置表对应的domain实体类生成的名称
                    tableName是数据库中的表名或视图名 -->
     
        <table tableName="categrey"
               domainObjectName="Categrey">
        </table>

    </context>
</generatorConfiguration>


3. 实体类

Categrey
package com.tina.gmalluser.product.entity;

import lombok.Data;

import java.io.Serializable;
import javax.persistence.*;

@Table(name = "categrey")
@Data
public class Categrey implements Serializable {
    @Id
    private String id;

    private String name;

    private String pid;

    public Categrey() {
    }

    public Categrey(String id, String name, String pid) {
        this.id = id;
        this.name = name;
        this.pid = pid;
    }
}
============================================================
CategreyQueryResp

package com.tina.gmalluser.product.resp;

import lombok.Data;

import java.util.List;

/**
 * @program: 谷粒商城
 * @description
 * @author: tina.liu
 * @create: 2020-02-08 15:32
 **/
@Data
public class CategreyQueryResp {

    private String id;

    private String name;

    private String pid;

    private List<CategreyQueryResp> categreyQueryRespList;

    public CategreyQueryResp() {
    }

    public CategreyQueryResp(String id, String name, String pid, List<CategreyQueryResp> categreyQueryRespList) {
        this.id = id;
        this.name = name;
        this.pid = pid;
        this.categreyQueryRespList = categreyQueryRespList;
    }

}
============================================================

4. dao

package com.tina.gmalluser.product.mapper;
import com.tina.gmalluser.product.entity.Categrey;
import tk.mybatis.mapper.common.Mapper;

@org.apache.ibatis.annotations.Mapper
public interface CategreyMapper extends Mapper<Categrey> {
}

5. service

public interface CategreyService {

    List<CategreyQueryResp> getAllCategrey(String s);
}
============================================================

package com.tina.gmalluser.product.service.impl;
import com.tina.gmalluser.product.entity.Categrey;
import com.tina.gmalluser.product.mapper.CategreyMapper;
import com.tina.gmalluser.product.resp.CategreyQueryResp;
import com.tina.gmalluser.product.service.CategreyService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: 谷粒商城
 * @description
 * @author: tina.liu
 * @create: 2020-02-08 15:27
 **/
@Service
public class CategreyServiceImpl implements CategreyService {

    @Resource
    private CategreyMapper categreyMapper;

  

    //@Override //查询所有的商品类别(使用三级查询)
    public List<CategreyQueryResp> getAllCategrey1(String id) {
        ///(1)根据已知的父ID查询到一级商品的所有类别,其父ID为 "0"
        //定义一个集合存储一级类别
        List<CategreyQueryResp> firstCategreyQueryRespList =new ArrayList<>();
        Categrey c1 = new Categrey();
        c1.setPid(id);
        List<Categrey> firstCategreyList = categreyMapper.select(c1);
        for (Categrey loop1:firstCategreyList) {
            CategreyQueryResp categreyQueryResp1 = new CategreyQueryResp();//有4个元素 id  pid name List<CategreyQueryResp>
            categreyQueryResp1.setId(loop1.getId());
            categreyQueryResp1.setName(loop1.getName());
            categreyQueryResp1.setPid(loop1.getPid());


            //(2)根据已知的父ID,查询到所有的二级商品的类别并将其封装到categreyQueryResp1类中,其父ID为loop1.getId()
            List<CategreyQueryResp> secondCategreyQueryRespList =new ArrayList<>();
            Categrey c2 = new Categrey();
            c2.setPid(loop1.getId());
            List<Categrey> secondeCategreyList = categreyMapper.select(c2);
            for (Categrey loop2:secondeCategreyList) {
                CategreyQueryResp categreyQueryResp2 = new CategreyQueryResp();//有4个元素 id  pid name List<CategreyQueryResp>
                categreyQueryResp2.setId(loop2.getId());
                categreyQueryResp2.setName(loop2.getName());
                categreyQueryResp2.setPid(loop2.getPid());

                //(3)根据已知的父ID,查询到所有的三级商品的类别并将其封装到categreyQueryResp22类中,其父ID为loop2.getId()
                List<CategreyQueryResp> thirdCategreyQueryRespList = new ArrayList<>();
                Categrey c3 = new Categrey();
                c3.setPid(loop2.getId());
                List<Categrey> categreyList3 = categreyMapper.select(c3);
                for (Categrey loop3:categreyList3) {
                    CategreyQueryResp   categreyQueryResp3 = new CategreyQueryResp();
                    categreyQueryResp3.setId(loop3.getId());
                    categreyQueryResp3.setName(loop3.getName());
                    categreyQueryResp3.setPid(loop3.getPid());
                    categreyQueryResp3.setCategreyQueryRespList(null);
                    thirdCategreyQueryRespList.add(categreyQueryResp3);
                }//三级循环
                categreyQueryResp2.setCategreyQueryRespList(thirdCategreyQueryRespList);
                secondCategreyQueryRespList.add(categreyQueryResp2);
            }//二级循环
            categreyQueryResp1.setCategreyQueryRespList(secondCategreyQueryRespList);
            firstCategreyQueryRespList.add(categreyQueryResp1);
        }//一级循环
        return firstCategreyQueryRespList;
    }



}//类的大括号


6. controller

package com.tina.gmalluser.product.controller;
import com.tina.gmalluser.product.except.Code;
import com.tina.gmalluser.product.except.EntityResp;
import com.tina.gmalluser.product.mapper.CategreyMapper;
import com.tina.gmalluser.product.resp.CategreyQueryResp;
import com.tina.gmalluser.product.service.CategreyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.spring.annotation.MapperScan;
import javax.annotation.Resource;
import java.util.List;

/**
 * @program: 谷粒商城
 * @description
 * @author: tina.liu
 * @create: 2020-02-08 15:26
 **/
@RestController
@RequestMapping(value = "/categrey")
@MapperScan(basePackages = "com.tina.gmalluser.product.mapper") //扫秒指定位置的mapper接口
@Api(value = "Categrey")
public class CategreyController {

    @Autowired
    private CategreyService categreyService;

    //查询所有的商品类别(使用三级查询)
    @GetMapping(value = "/getAllCategrey")
    @ApiOperation(value = "查询所有的商品类别(使用三级查询)")
    public EntityResp<Object> getAllCategrey(){
       List<CategreyQueryResp> categreyQueryRespList = categreyService.getAllCategrey("0");
       return new EntityResp<>(categreyQueryRespList, Code.SERVER_SUCCESS);
    }
 
}//类的大括号

7. 测试类

package com.tina.gmalluser.product.controller;
import com.tina.gmalluser.GmallProduct;
import com.tina.gmalluser.product.entity.Categrey;
import com.tina.gmalluser.product.mapper.CategreyMapper;
import com.tina.gmalluser.product.resp.CategreyQueryResp;
import com.tina.gmalluser.product.service.CategreyService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import tk.mybatis.spring.annotation.MapperScan;
import java.util.List;
/**
 * @program: 谷粒商城
 * @description
 * @author: tina.liu
 * @create: 2020-02-08 17:17
 **/
@RunWith(SpringJUnit4ClassRunner.class) //junit单元测试
@org.springframework.boot.test.context.SpringBootTest(classes =GmallProduct.class )
public  class SpringBootTest {

}//类的大括号

递归查询


    //定义递归查询的方法
    public List<SubjectResp> getList(String parentId){
        //定义一个集合
        List<SubjectResp> subjectRespList = new ArrayList<>();

        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentId);
        List<Subject> list = subjectService.list(wrapper);
        for (Subject subject : list) {
            SubjectResp subjectResp = new SubjectResp();
            BeanUtils.copyProperties(subject,subjectResp);
            QueryWrapper<Subject> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("parent_id",subject.getId());
            List<Subject> childList = subjectService.list(wrapper2);
            List<SubjectResp> child = new ArrayList<>();
            if(childList.isEmpty()){
                subjectResp.setChild(null);
                subjectRespList.add(subjectResp);
                rcontinue;//结束本次循环
            }else {
                for (Subject loop : childList) {
                    SubjectResp subjectResp2 = new SubjectResp();
                    BeanUtils.copyProperties(loop,subjectResp2);
                    List<SubjectResp> list1 = getList(loop.getId());
                    subjectResp2.setChild(list1);
                    child.add(subjectResp2);
                }
            }
            subjectResp.setChild(child);
            subjectRespList.add(subjectResp);
        }
        return subjectRespList;
    }



上一篇 下一篇

猜你喜欢

热点阅读