首页 > 其他分享 >Spring JdbcTemplate+Druid数据源+FreeMarker 开发代码生成器

Spring JdbcTemplate+Druid数据源+FreeMarker 开发代码生成器

时间:2024-03-19 18:58:22浏览次数:33  
标签:代码生成 return String FreeMarker beanParam 数据源 beanName import public

虽然在这个时代,几乎所有成熟的开发框架都自带代码生成器,但有时候我们难免会遇到没有代码生成器的开发框架,这个时候,自己手中有一套代码生成器,把模版文件调整一下立马就能用,这就比较惬意了。

这里讲一下如何利用Spring JdbcTemplate+Druid数据源+FreeMarker 开发一套代码生成器。

1、新建maven项目create-code

2、pom文件配置

<?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>

    <groupId>org.wuql</groupId>
    <artifactId>create-code</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- 引入Spring-AOP等相关Jar -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>3.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</project>

3、数据源spring.xml配置

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
     	 http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 开启注解 -->
    <context:component-scan
            base-package="com.wuql.create"></context:component-scan>
    <!-- druid数据源 -->
    <bean id="dataSource"
          class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/ruoyi?useUnicode=true&amp;characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <!-- jdbcTemplate数据源 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

4、数据表字段属性类

package com.wuql.create.bean;

import lombok.Data;

/**
 * 数据表字段属性
 * @author : wuQingLiang
 * @date : 2024/3/14
 **/
@Data
public class ClassColumn {

    private String columnName;//数据表字段名称java驼峰写法

    private String columnNameLine;//数据表字段的实际名称

    private String dataType;//数据表字段类型

    private String columnComment;//数据表字段注释
}

5、Dao层实现 使用JdbcTemplate

package com.wuql.create.dao;

import com.wuql.create.bean.ClassColumn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author : wuQingLiang
 * @date : 2024/3/14
 **/
@Repository
public class ColumnDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     *  查询数据表所有字段的名称、数据类型、注释
     * @param table_schema 数据库名称
     * @param tableName 数据表名称
     * @return
     */
    public List<ClassColumn> queryColumnList(String table_schema,String tableName){
        String sql = "select lower(column_name)as column_name_line, lower(data_type) as data_type,column_comment from information_schema.columns where table_schema = ? and  table_name = ?";
        List<ClassColumn> list = jdbcTemplate.query(sql, new Object[]{table_schema,tableName}, new BeanPropertyRowMapper<ClassColumn>(ClassColumn.class));
        return list;
    }

    /**
     * 查询数据表主键的名称、数据类型、注释
     * @param table_schema 数据库名称
     * @param tableName 数据表名称
     * @return
     */
    public ClassColumn getTableKey(String table_schema,String tableName){
        String sql = "select lower(column_name)as column_name_line, lower(data_type) as data_type,column_comment from information_schema.columns where table_schema = ? and  table_name = ? and  column_key = 'PRI'";
        List<ClassColumn> list = jdbcTemplate.query(sql, new Object[]{table_schema,tableName}, new BeanPropertyRowMapper<ClassColumn>(ClassColumn.class));
        ClassColumn keyColumn=new ClassColumn();
        if(list.size()>0){
            keyColumn=list.get(0);
        }else{
            throw new RuntimeException(tableName+"表没有主键!");
        }
        return keyColumn;
    }
}

6、Service层实现及工具类

6.1 ColumnService service层逻辑实现

package com.wuql.create.service;

import com.wuql.create.bean.ClassColumn;
import com.wuql.create.dao.ColumnDao;
import com.wuql.create.util.ToJavaType;
import com.wuql.create.util.UnderlineToCamelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : wuQingLiang
 * @date : 2024/3/14
 **/
@Service
public class ColumnService {
    @Autowired
    private ColumnDao columnDao;

    /**
     * 查询数据表所有字段的名称、数据类型、注释
     *
     * @param table_schema 数据库名称
     * @param tableName    数据表名称
     * @return
     */
    public List<ClassColumn> queryColumnList(String table_schema, String tableName) {
        //查询数据表所有字段的名称、数据类型、注释
        List<ClassColumn> classColumnList = columnDao.queryColumnList(table_schema, tableName);
        for (ClassColumn classColumn : classColumnList) {
            //数据库字段名称转Java驼峰名称
            String columnName = UnderlineToCamelUtils.underlineToCamel(classColumn.getColumnNameLine());
            //数据库字段类型转Java数据类型
            String dataType = ToJavaType.mysqlTypeToJavaType(classColumn.getDataType());
            classColumn.setColumnName(columnName);
            classColumn.setDataType(dataType);
        }
        return classColumnList;
    }

    /**
     * 查询数据表主键的名称、数据类型、注释
     *
     * @param table_schema 数据库名称
     * @param tableName    数据表名称
     * @return
     */
    public ClassColumn getTableKey(String table_schema, String tableName) {
        ClassColumn classColumn = columnDao.getTableKey(table_schema, tableName);
        //数据库字段名称转Java驼峰名称
        String columnName = UnderlineToCamelUtils.underlineToCamel(classColumn.getColumnNameLine());
        //数据库字段类型转Java数据类型
        String dataType = ToJavaType.mysqlTypeToJavaType(classColumn.getDataType());
        classColumn.setColumnName(columnName);
        classColumn.setDataType(dataType);
        return classColumn;
    }
}

6.2 FreeMarkerUtil freeMarker生成文件工具类

package com.wuql.create.util;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Locale;
import java.util.Map;

/**
 * FreeMarker模版生成文件工具类
 * @author : wuQingLiang
 * @date : 2024/3/14
 **/
public class FreeMarkerUtil {

    /**
     *
     * @param data 供模版用的动态数据
     * @param templateName 模版名称
     * @param savePath 生成文件的保存路径 全路径 包含生成文件名
     */
    public static void createFile(Map<String,Object> data,String templateName,String savePath){
        try {
            Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            cfg.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates");
            cfg.setEncoding(Locale.CHINA, "UTF-8");
            Template template = cfg.getTemplate(templateName, "UTF-8");
            StringWriter writer = new StringWriter();
            template.process(data, writer);
            writer.flush();
            String content = writer.toString();
            Path path = Paths.get(savePath);
            Files.createDirectories(path.getParent());
            Files.write(path, content.getBytes());
        }catch (Exception e){
           System.out.println(e.getMessage());
        }
    }
}

6.3 ToJavaType 数据库字段类型转Java类型

package com.wuql.create.util;


/**
 * 数据表字段类型转Java类型工具类
 * @author : wuQingLiang
 * @date : 2024/3/14
 **/
public class ToJavaType {
    /**
     * mysql字段类型转Java类型
     * @param mysqlType mysql数据库字段类型名称
     * @return
     */
    public static String mysqlTypeToJavaType(String mysqlType) {
        switch (mysqlType) {
            case "int":
                return "Integer";
            case "bigint":
                return "Long";
            case "decimal":
            case "float":
            case "double":
                return "Double";
            case "varchar":
            case "char":
            case "text":
            case "tinyint":
            case "blob":
            case "longblob":
                return "String";
            case "date":
            case "time":
            case "timestamp":
            case "datetime":
                return "Date";
            case "bit":
                return "Boolean";
            default:
                return "Unknown Type";
        }
    }

    /**
     *  pgsql字段类型转Java类型
     * @param pgsqlType  pgsql数据库字段类型名称
     * @return
     */
    public static String pgsqlTypeToJavaType(String pgsqlType) {
        switch (pgsqlType) {
            case "int":
                return "Integer";
            case "bigint":
                return "Long";
            case "decimal":
            case "float":
            case "double":
            case "double precision":
                return "Double";
            case "varchar":
            case "char":
            case "text":
            case "tinyint":
            case "blob":
                return "String";
            case "date":
            case "time":
            case "timestamp":
            case "datetime":
            case "timestamp without time zone":
                return "Date";
            case "bit":
            case "boolean":
                return "Boolean";
            default:
                return "Unknown Type";
        }
    }
}

6.4 UnderlineToCamelUtils 数据库字段名转Java驼峰

package com.wuql.create.util;

/**
 * 数据库字段名称转Java驼峰名称工具类
 * @author : wuQingLiang
 * @date : 2024/3/14
 **/
public class UnderlineToCamelUtils {
    /**
     * 数据库字段下划线转Java驼峰
     * @param line 数据库数据表字段名称 带下划线的转驼峰
     * @return
     */
    public static String underlineToCamel(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        // 正则表达式分割
        String[] lines = line.split("_");
        for (int i = 0; i < lines.length; i++) {
            if(i==0){
                sb.append(lines[0].toLowerCase());
            }else{
                // 将第一个字母转换为大写
                sb.append(Character.toUpperCase(lines[i].charAt(0)));
                // 将后续字母转换为小写
                sb.append(lines[i].substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }

    /**
     * 参数名称  类名 首字母转小写
     * @param beanName 实体类名
     * @return
     */
    public static String firstCharToLower(String beanName) {
        if (beanName == null || "".equals(beanName)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        sb.append(Character.toLowerCase(beanName.charAt(0)));
        sb.append(beanName.substring(1));
        return sb.toString();
    }
}

7、FreeMarker模版文件

这里以若依框架的后端为模版,各位可以根据实际情况自行修改模版文件。

7.1 bean.ftl

package ${(packageStr)!''}.bean;

import lombok.Data;
import java.util.Date;
/**
* @author : wuQingLiang
* @date : 2024/3/14
**/
@Data
public class ${(beanName)!''} {

<#list columnList as column>
    /** ${(column.columnComment)!''} */
    private ${(column.dataType)!''} ${(column.columnName)!''};
</#list>

}

7.2 controller.ftl

package ${(packageStr)!''}.controller;

import java.util.List;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ${(packageStr)!''}.bean.${(beanName)!''};
import ${(packageStr)!''}.service.${(beanName)!''}Service;


@RestController
@RequestMapping("/${(beanParam)!''}")
public class ${(beanName)!''}Controller extends BaseController
{
    @Autowired
    private ${(beanName)!''}Service ${(beanParam)!''}Service;


    @GetMapping("/list")
    public TableDataInfo list(${(beanName)!''} ${(beanParam)!''})
    {
        startPage();
        List<${(beanName)!''}> list = ${(beanParam)!''}Service.select${(beanName)!''}List(${(beanParam)!''});
        return getDataTable(list);
    }


    @GetMapping(value = "/{${keyColumn.columnName}}")
    public AjaxResult getInfo(@PathVariable Long ${keyColumn.columnName})
    {
        return success(${(beanParam)!''}Service.select${(beanName)!''}ById(${keyColumn.columnName}));
    }


    @PostMapping
    public AjaxResult add(@Validated @RequestBody ${(beanName)!''} ${(beanParam)!''})
    {
        ${(beanParam)!''}.setCreateBy(getUsername());
        return toAjax(${(beanParam)!''}Service.insert${(beanName)!''}(${(beanParam)!''}));
    }

    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ${(beanName)!''} ${(beanParam)!''})
    {
        ${(beanParam)!''}.setUpdateBy(getUsername());
        return toAjax(${(beanParam)!''}Service.update${(beanName)!''}(${(beanParam)!''}));
    }


    @DeleteMapping("/{${keyColumn.columnName}s}")
    public AjaxResult remove(@PathVariable Long[] ${keyColumn.columnName}s)
    {
        return toAjax(${(beanParam)!''}Service.delete${(beanName)!''}ByIds(${keyColumn.columnName}s));
    }
}

7.3 mapper.ftl

package ${(packageStr)!''}.mapper;

import java.util.List;
import ${(packageStr)!''}.bean.${(beanName)!''};


public interface ${(beanName)!''}Mapper
{

    public ${(beanName)!''} select${(beanName)!''}ById(Long ${keyColumn.columnName});


    public List<${(beanName)!''}> select${(beanName)!''}List(${(beanName)!''} ${(beanParam)!''});


    public int insert${(beanName)!''}(${(beanName)!''} ${(beanParam)!''});


    public int update${(beanName)!''}(${(beanName)!''} ${(beanParam)!''});


    public int delete${(beanName)!''}ById(Long ${keyColumn.columnName});


    public int delete${(beanName)!''}ByIds(Long[] ${keyColumn.columnName}s);

}

7.4 service.ftl

package ${(packageStr)!''}.service;

import java.util.List;
import ${(packageStr)!''}.bean.${(beanName)!''};

public interface ${(beanName)!''}Service
{

    public ${(beanName)!''} select${(beanName)!''}ById(Long ${keyColumn.columnName});


    public List<${(beanName)!''}> select${(beanName)!''}List(${(beanName)!''} ${(beanParam)!''});


    public int insert${(beanName)!''}(${(beanName)!''} ${(beanParam)!''});


    public int update${(beanName)!''}(${(beanName)!''} ${(beanParam)!''});


    public int delete${(beanName)!''}ById(Long ${keyColumn.columnName});


    public int delete${(beanName)!''}ByIds(Long[] ${keyColumn.columnName}s);
    }

7.5 serviceImpl.ftl

package ${(packageStr)!''}.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ${(packageStr)!''}.bean.${(beanName)!''};
import ${(packageStr)!''}.mapper.${(beanName)!''}Mapper;
import ${(packageStr)!''}.service.${(beanName)!''}Service;


@Service
public class ${(beanName)!''}ServiceImpl implements ${(beanName)!''}Service
{
    @Autowired
    private ${(beanName)!''}Mapper ${(beanParam)!''}Mapper;


    @Override
    public ${(beanName)!''} select${(beanName)!''}ById(Long ${(beanParam)!''})
    {
        return ${(beanParam)!''}Mapper.select${(beanName)!''}ById(${(beanParam)!''});
    }


    @Override
    public List<${(beanName)!''}> select${(beanName)!''}List(${(beanName)!''} ${(beanParam)!''})
    {
        return ${(beanParam)!''}Mapper.select${(beanName)!''}List(${(beanParam)!''});
    }


    @Override
    public int insert${(beanName)!''}(${(beanName)!''} ${(beanParam)!''})
    {
        return ${(beanParam)!''}Mapper.insert${(beanName)!''}(${(beanParam)!''});
    }


    @Override
    public int update${(beanName)!''}(${(beanName)!''} ${(beanParam)!''})
    {
        return ${(beanParam)!''}Mapper.update${(beanName)!''}(${(beanParam)!''});
    }


    @Override
    public int delete${(beanName)!''}ById(Long ${keyColumn.columnName})
    {
        return ${(beanParam)!''}Mapper.delete${(beanName)!''}ById(${keyColumn.columnName});
    }


    @Override
    public int delete${(beanName)!''}ByIds(Long[] ${keyColumn.columnName}s)
    {
        return ${(beanParam)!''}Mapper.delete${(beanName)!''}ByIds(${keyColumn.columnName}s);
    }
}

7.6 xml.ftl

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${(packageStr)!''}.mapper.${(beanName)!''}Mapper">

    <resultMap type="${(packageStr)!''}.bean.${(beanName)!''}" id="${(beanName)!''}Result">
        <#list columnList as column>
            <result property="${(column.columnName)!''}"       column="${(column.columnNameLine)!''}"       />
        </#list>
    </resultMap>

    <sql id="select${(beanName)!''}">
        select  <#list columnList as column><#if column_index < columnList?size-1 >${(column.columnNameLine)!''},<#else>${(column.columnNameLine)!''}</#if></#list>
        from ${(tableName)!''}
    </sql>

    <select id="select${(beanName)!''}ById" parameterType="Long" resultMap="${(beanName)!''}Result">
        <include refid="select${(beanName)!''}"/>
        where ${r'#{'}${keyColumn.columnNameLine}${r'}'} = ${r'#{'}${keyColumn.columnName}${r'}'}
    </select>

    <select id="select${(beanName)!''}List" parameterType="${(packageStr)!''}.bean.${(beanName)!''}" resultMap="${(beanName)!''}Result">
        <include refid="select${(beanName)!''}"/>
        <where>
            <#list columnList as column>
            <if test="${(column.columnName)!''} != null and ${(column.columnName)!''} != ''">
                AND ${column.columnNameLine} = ${r'#{'}${(column.columnName)!''}${r'}'}
            </if>
            </#list>
        </where>
    </select>

    <insert id="insert${(beanName)!''}" parameterType="${(packageStr)!''}.bean.${(beanName)!''}">
        insert into ${(tableName)!''} (
        <#list columnList as column>
            <if test="${(column.columnName)!''} != null and ${(column.columnName)!''} != '' ">${(column.columnNameLine)!''}, </if>
        </#list>
        )values(
        <#list columnList as column>
            <if test="${(column.columnName)!''} != null and ${(column.columnName)!''} != ''">${r'#{'}${(column.columnName)!''}${r'}'}, </if>
        </#list>
        )
    </insert>

    <update id="update${(beanName)!''}" parameterType="${(packageStr)!''}.bean.${(beanName)!''}">
        update ${(tableName)!''}
        <set>
            <#list columnList as column>
            <if test="${(column.columnName)!''} != null and ${(column.columnName)!''} != ''">${(column.columnNameLine)!''} = ${r'#{'}${(column.columnName)!''}${r'}'}, </if>
            </#list>
        </set>
        where ${r'#{'}${keyColumn.columnNameLine}${r'}'} = ${r'#{'}${keyColumn.columnName}${r'}'}
    </update>

    <delete id="delete${(beanName)!''}ById" parameterType="Long">
        delete from ${(tableName)!''} where ${r'#{'}${keyColumn.columnNameLine}${r'}'} =  ${r'#{'}${keyColumn.columnName}${r'}'}
    </delete>

    <delete id="delete${(beanName)!''}ByIds" parameterType="Long">
        delete from ${(tableName)!''} where ${r'#{'}${keyColumn.columnNameLine}${r'}'} in
        <foreach item="${keyColumn.columnName}" collection="array" open="(" separator="," close=")">
            ${r'#{'}${keyColumn.columnName}${r'}'}
        </foreach>
    </delete>

</mapper>

8、主程序CreateCode

package com.wuql.create;

import com.wuql.create.bean.ClassColumn;
import com.wuql.create.service.ColumnService;
import com.wuql.create.util.FreeMarkerUtil;
import com.wuql.create.util.UnderlineToCamelUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成工具
 * @author : wuQingLiang
 * @date : 2024/3/14
 **/
public class CreateCode {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        ColumnService columnService =(ColumnService) applicationContext.getBean("columnService");
        /********************以下参数执行时需要根据实际项目修改**************************/
        String tableSchema="ruoyi";   //mysql数据库名称
        String tableName="shop_goods"; //数据表名称
        String beanName="Goods";  //要生成的实体类名称
        String rootPath="E:/worknew/ruo-yi-demo/ruoyi-shop"; //生成的代码保存根目录
        String packageStr="com.ruoyi.shop"; //生成的代码保存包路径
        /********************以上参数执行时需要根据实际项目修改**************************/

        /********************以下代码一般不需要修改**************************/
        String basePath=rootPath+"/src/main/java/"+packageStr.replace(".","/");
        String beanPath=basePath+"/bean/"+beanName+".java";
        String mapperPath=basePath+"/mapper/"+beanName+"Mapper.java";
        String servicePath=basePath+"/service/"+beanName+"Service.java";
        String controllerPath=basePath+"/controller/"+beanName+"Controller.java";
        String serviceImplPath=basePath+"/service/impl/"+beanName+"ServiceImpl.java";
        String xmlPath=rootPath+"/src/main/resources/mapper/"+beanName+"Mapper.xml";
        List<ClassColumn> columnList=columnService.queryColumnList(tableSchema,tableName);//数据表所有字段
        ClassColumn keyColumn=columnService.getTableKey(tableSchema,tableName);//数据表主键
        String beanParam= UnderlineToCamelUtils.firstCharToLower(beanName);//参数名称
        Map<String,Object> data = new HashMap<>();
        data.put("packageStr", packageStr);
        data.put("beanName", beanName);
        data.put("beanParam", beanParam);
        data.put("tableName", tableName);
        data.put("columnList", columnList);
        data.put("keyColumn", keyColumn);

        /********************以下ftl模版内容可根据实际项目修改**************************/
        FreeMarkerUtil.createFile(data,"bean.ftl",beanPath);//创建bean
        FreeMarkerUtil.createFile(data,"xml.ftl",xmlPath);//创建mapper.xml
        FreeMarkerUtil.createFile(data,"mapper.ftl",mapperPath);//创建mapper.java
        FreeMarkerUtil.createFile(data,"service.ftl",servicePath);//创建service.java
        FreeMarkerUtil.createFile(data,"serviceImpl.ftl",serviceImplPath);//创建serviceImpl.java
        FreeMarkerUtil.createFile(data,"controller.ftl",controllerPath);//创建controller.java
        System.out.println("--------代码生成成功,请打开文件路径"+rootPath+"查看生成的代码文件---------");

    }
}

9、项目目录结构

10、运行后生成的代码效果

 运行:

 结果:

标签:代码生成,return,String,FreeMarker,beanParam,数据源,beanName,import,public
From: https://blog.csdn.net/wuqingliang510/article/details/136851072

相关文章

  • 多数据源加密(90%来自文心一言)
    在dynamic-datasource-spring-boot-starter3.2.0中,如果你希望对加密的密码进行自定义解密,你需要实现自己的PropertySourceLocator或者自定义配置解析逻辑,以便在读取配置时能够自动解密密码。以下是实现自定义解密逻辑的一般步骤:创建自定义的解密工具类首先,你需要一个能......
  • 【Database】基于Mybatis的多数据源连接实现方式
    场景出于种种原因有些时候我们的项目中会用到同时连接多个数据源的情况,比如数据太大了分了多个库,又比如统计任务只能读原始数据的数据库,写只能在统计结果的库中。设计思路基于mybatis我们的方案是这样的,需要自己实现一个SqlSessionTemplate,里面维护了一个dbId到SqlSessionFact......
  • 【Database】可选的数据源配置项
    【Database】可选的数据源配置项场景之前的版本中没有数据源依赖,新版本中有数据源依赖,只有部分模块需要配置数据源,其余模块仍然读老的配置,如果使用自动装配的mybatis会启动报错。方案通过一个默认为false的开关控制数据源的加载@Configuration@MapperScan(basePackages={"......
  • 【业务功能篇】多环境配置、多数据源切换失效@DS解决方式
     多环境配置通过resources资源目录--config目录,我们分成了开发生产测试三个,不过一般我们都是测试环境进行测试数据库,本地开发环境就是连接测试环境 根据三个不同的环境,注意命名规范:application-xxx.yml,这样在我们的app配置文件就可以指定后缀这个值xxx就表示要运行哪个......
  • MybatisPlus[新]逆向工程,代码生成器
    MybatisPlus旧版本的代码生成器官方新版已经不在维护了.并在新版中,将内部的构造方法改成了private,导致新版本的myabtis-plus无法使用旧版本的代码生成器.下列配置是新版本的代码生成配置添加依赖<!--代码自动生成器依赖--><dependency><groupId>com.baomidou</......
  • mybatis-plus代码生成
    添加依赖:<!--代码自动生成器依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.3.1</version></dependency><dependency><gro......
  • springboot配置多个数据源,导致分页插件失效,返回的total为0
    直接在sqlSessionFactoryBean中指定分页插件packagecom.gs.asset.config;importcom.alibaba.druid.pool.DruidDataSource;importcom.baomidou.mybatisplus.annotation.DbType;importcom.baomidou.mybatisplus.autoconfigure.SpringBootVFS;importcom.baomidou.mybatis......
  • 中间代码生成(Intermediate Code Generation)
    目录在编译器设计中,将高级语言代码(如C、C++、Java等)转换为低级语言(如汇编语言或机器语言)是一个复杂的过程,其中包括对不同类型的语句进行翻译。下面我将简要解释你提到的各种语句的翻译过程:声明语句的翻译:声明语句用于定义变量、类型或函数。在翻译时,编译器会为这些实体在符......
  • MyBatisPlus代码生成器(新)
    MyBatisPlus代码生成器(新)注意:适用版本:mybatis-plus-generator3.5.1以上版本参考:官网本次配置:JDK17+SpringBoot3.1.5+MyBatisPlus3.5.3.1注意:mybatis-plus-generator版本需与mybatis-plus版本一致最新依赖参考:https://mvnrepository.com/artifact/com.baomid......
  • 代码生成器之如何快速生成后端接口?
    前言在现代软件开发中,重复性的增删改查逻辑代码的编写往往非常耗时且容易出错。为了提高开发效率,减少手动维护的成本,代码生成器就成为了一个非常重要的工具,本文小编就将为大家介绍一下如何利用一个开源项目快速生成数据接口。实现方式环境准备技术栈:Java,Spring-Boot,MyBatisPlu......