mybatis-plus 代码生成器,自定义不需要接口和实现类的service类

对于业务相对简单,一个service接口只对应一个实现类的话,可以不写service接口,直接定义service业务类
1、引入jar包

        <!-- MYSQL -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- Spring Boot JDBC -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<!--Mybatis-Plus 注意版本-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.1</version>
		</dependency>
		<!--Mybatis-Plus 代码生成器-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.3.2</version>
		</dependency>
		<!--模板引擎-->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.30</version>
		</dependency>

2、properties配置

#mysql
spring.datasource.url=jdbc:mysql:/localhost:3306/ease-run?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#mybatis-plus
mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.type-aliases-package=com.tomato.admin.entity
mybatis-plus.configuration.map-underscore-to-camel-case: true

3、自定义service
①创建自定义模板

package ${package.Service};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;

/**
 * <p>
 * $!{table.comment} 服务类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Service
public class ${table.serviceName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> {

		}

②引入模板

// 下面这行自定义Service类,因为自带模板的是Service接口+实现类,这里只想要Service类,不想要接口,所以自定义Service模板
		String serviceTemplatePath = "/templates/vm/myService.java.vm";

		// 自定义输出配置
		List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
		// 自定义Service类
		focList.add(new FileOutConfig(serviceTemplatePath) {
			@Override
			public String outputFile(TableInfo tableInfo) {
				// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
				return projectPath + "/tomato-bean/src/main/java/com/tomato/tomatobean/service/" + pc.getModuleName()
						+ "/" + tableInfo.getEntityName() + "Service" + StringPool.DOT_JAVA;

			}
		});

③完整的代码生成器代码

package com.tomato.tomatobean.generator;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang.StringUtils;

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

/**
 * @program: tomato
 * @description: 代码生成器
 * @author: wujs
 * @create: 2021-09-16 14:08
 */
public class CodeGenerator {

	public static void main(String[] args) {
		// 代码生成器
		AutoGenerator mpg = new AutoGenerator();

		// 全局配置
		GlobalConfig gc = new GlobalConfig();
		final String projectPath = System.getProperty("user.dir");
		gc.setOutputDir(projectPath + "/tomato-bean/src/main/java");
		gc.setAuthor("wujs");
		gc.setOpen(false);

		gc.setFileOverride(false);//是否覆盖
		gc.setServiceName("%sService");//去除Service的I前缀
		gc.setIdType(IdType.INPUT);//主键类型
		gc.setDateType(DateType.ONLY_DATE);//日期类型

		// gc.setSwagger2(true); 实体属性 Swagger2 注解
		mpg.setGlobalConfig(gc);

		// 数据源配置
		DataSourceConfig dsc = new DataSourceConfig();
		dsc.setUrl("jdbc:mysql://localhost:3306/tomato?useUnicode=true&useSSL=false&characterEncoding=utf8");
		// dsc.setSchemaName("public");
		dsc.setDriverName("com.mysql.jdbc.Driver");
		dsc.setUsername("root");
		dsc.setPassword("root");
		mpg.setDataSource(dsc);

		// 包配置
		final PackageConfig pc = new PackageConfig();
		pc.setParent("com.tomato.tomatobean");
		mpg.setPackageInfo(pc);

		// 自定义配置
		InjectionConfig cfg = new InjectionConfig() {
			@Override
			public void initMap() {
				// to do nothing
			}
		};

		// 如果模板引擎是 freemarker
		String templatePath = "/templates/mapper.xml.ftl";
		// 如果模板引擎是 velocity
		// String templatePath = "/templates/mapper.xml.vm";

		// 自定义Service模板 文件名
		gc.setServiceName("%sService");

		// 配置模板
		TemplateConfig templateConfig = new TemplateConfig();

		// 关闭原有生成
		templateConfig.setService(null);
		templateConfig.setServiceImpl(null);


		// 下面这行自定义Service类,因为自带模板的是Service接口+实现类,这里只想要Service类,不想要接口,所以自定义Service模板
		String serviceTemplatePath = "/templates/vm/myService.java.vm";

		// 自定义输出配置
		List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
		// 自定义Service类
		focList.add(new FileOutConfig(serviceTemplatePath) {
			@Override
			public String outputFile(TableInfo tableInfo) {
				// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
				return projectPath + "/tomato-bean/src/main/java/com/tomato/tomatobean/service/" + pc.getModuleName()
						+ "/" + tableInfo.getEntityName() + "Service" + StringPool.DOT_JAVA;

			}
		});
		//xml文件输出位置
		focList.add(new FileOutConfig(templatePath) {
			@Override
			public String outputFile(TableInfo tableInfo) {
				// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
				return projectPath + "/tomato-bean/src/main/resources/mapper/" + pc.getModuleName()
						+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
			}
		});
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
		cfg.setFileOutConfigList(focList);
		mpg.setCfg(cfg);


		// 配置自定义输出模板
		//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
		// templateConfig.setEntity("templates/entity2.java");
		// templateConfig.setService();
		// templateConfig.setController();

		templateConfig.setXml(null);
		mpg.setTemplate(templateConfig);

		// 策略配置
		StrategyConfig strategy = new StrategyConfig();
		strategy.setNaming(NamingStrategy.underline_to_camel);
		strategy.setColumnNaming(NamingStrategy.underline_to_camel);
		//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
		//strategy.setEntityLombokModel(true);//lombak
		strategy.setRestControllerStyle(true);
		// 公共父类
		//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
		// 写于父类中的公共字段
		strategy.setSuperEntityColumns("id");
		strategy.setInclude("ums_admin");
		//	strategy.setControllerMappingHyphenStyle(true);
		// @TableName注解
		strategy.setEntityTableFieldAnnotationEnable(true);
		mpg.setStrategy(strategy);
		mpg.setTemplateEngine(new FreemarkerTemplateEngine());
		mpg.execute();
	}
}

4、执行结果,只有service的业务类,没有接口和实现类
在这里插入图片描述

MyBatis-Plus代码生成器提供了自定义模板的功能,可以根据自己的需求生成对应的代码。下面是自定义模板的处理步骤: 1. 在代码生成器的配置文件中,设置自定义模板的路径。例如: ``` <property name="templatePath" value="/templates/mybatis-plus"/> ``` 2. 在自定义模板路径下创建对应的模板文件。例如,创建一个模板文件 `Entity.java.vm`,用于生成实体的代码。 3. 在模板文件中使用 Velocity 模板语言,编写生成代码的逻辑。例如: ``` package ${package_name}.${module_name}.entity; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * ${table_comment} * </p> */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("${table_name}") public class ${entity_name} { private static final long serialVersionUID = 1L; #foreach($field in $fields) /** * ${field.comment} */ private ${field.javaType} ${field.name}; #end } ``` 4. 在代码生成器中配置要使用的自定义模板。例如: ``` <property name="templateConfig"> <bean class="com.baomidou.mybatisplus.generator.config.TemplateConfig"> <property name="entity" value="/templates/mybatis-plus/Entity.java.vm"/> <property name="mapper" value="/templates/mybatis-plus/Mapper.java.vm"/> <property name="xml" value="/templates/mybatis-plus/Mapper.xml.vm"/> <property name="service" value="/templates/mybatis-plus/Service.java.vm"/> <property name="serviceImpl" value="/templates/mybatis-plus/ServiceImpl.java.vm"/> <property name="controller" value="/templates/mybatis-plus/Controller.java.vm"/> </bean> </property> ``` 在这个例子中,我们配置了生成实体、Mapper接口、Mapper XML文件、Service接口Service实现和Controller的模板路径。 5. 运行代码生成器,即可根据自定义模板生成对应的代码。 注意:自定义模板的命名必须与 MyBatis-Plus 内置模板的命名一致,才能正确覆盖内置模板。例如,要自定义生成实体的模板,必须将模板文件命名为 `Entity.java.vm`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值