In this chapter, we use Freemarker to automatically generate service, serviceImpl, and Controller functions. If you have any questions, please contact me at [email protected]. Ask for directions of various gods, thank you
One: Add a Freemarker dependency
< the dependency > < groupId > org. Freemarker < / groupId > < artifactId > freemarker < / artifactId > < version > 2.3.28 < / version > </dependency>Copy the code
Create service, serviceImpl, and Controller templates
Create under SRC \test\ Java \resources\template\generator
service.ftl
package ${basePackageService};
import ${basePackageModel}.${modelNameUpperCamel};
import ${basePackage}.core.universal.Service;
/**
* @Description: ${modelNameUpperCamel}Service interface * @author${author}
* @date ${date}
*/
public interface ${modelNameUpperCamel}Service extends Service<${modelNameUpperCamel}> {}Copy the code
service-impl.ftl
package ${basePackageServiceImpl};
import ${basePackageDao}.${modelNameUpperCamel}Mapper;
import ${basePackageModel}.${modelNameUpperCamel};
import ${basePackageService}.${modelNameUpperCamel}Service;
import ${basePackage}.core.universal.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* @Description: ${modelNameUpperCamel}Service interface implementation class * @author${author}
* @date ${date}
*/
@Service
public class ${modelNameUpperCamel}ServiceImpl extends AbstractService<${modelNameUpperCamel}> implements ${modelNameUpperCamel}Service {
@Resource
private ${modelNameUpperCamel}Mapper ${modelNameLowerCamel}Mapper;
}Copy the code
controller.ftl
package ${basePackageController};
import ${basePackage}.core.ret.RetResult;
import ${basePackage}.core.ret.RetResponse;
import ${basePackageModel}.${modelNameUpperCamel};
import ${basePackageService}.${modelNameUpperCamel}Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* @Description: ${modelNameUpperCamel}The Controller class * @ the author${author}
* @date ${date}
*/
@RestController
@RequestMapping("/${baseRequestMapping}")
public class ${modelNameUpperCamel}Controller {
@Resource
private ${modelNameUpperCamel}Service ${modelNameLowerCamel}Service;
@PostMapping("/insert")
public RetResult<Integer> insert(${modelNameUpperCamel} ${modelNameLowerCamel}) throws Exception{
Integer state = ${modelNameLowerCamel}Service.insert(${modelNameLowerCamel});
return RetResponse.makeOKRsp(state);
}
@PostMapping("/deleteById")
public RetResult<Integer> deleteById(@RequestParam String id) throws Exception {
Integer state = ${modelNameLowerCamel}Service.deleteById(id);
return RetResponse.makeOKRsp(state);
}
@PostMapping("/update")
public RetResult<Integer> update(${modelNameUpperCamel} ${modelNameLowerCamel}) throws Exception {
Integer state = ${modelNameLowerCamel}Service.update(${modelNameLowerCamel});
return RetResponse.makeOKRsp(state);
}
@PostMapping("/selectById")
public RetResult<${modelNameUpperCamel}> selectById(@RequestParam String id) throws Exception {
${modelNameUpperCamel} ${modelNameLowerCamel} = ${modelNameLowerCamel}Service.selectById(id);
return RetResponse.makeOKRsp(${modelNameLowerCamel}); } /** * @description: paging query * @param page number * @param size number of pages per page * @reutrn RetResult<PageInfo<${modelNameUpperCamel}>>
*/
@PostMapping("/list")
public RetResult<PageInfo<${modelNameUpperCamel}>> list(@RequestParam(defaultValue = "0") Integer page,
@RequestParam(defaultValue = "0") Integer size) throws Exception {
PageHelper.startPage(page, size);
List<${modelNameUpperCamel}> list = ${modelNameLowerCamel}Service.selectAll();
PageInfo<${modelNameUpperCamel}> pageInfo = new PageInfo<${modelNameUpperCamel}>(list);
returnRetResponse.makeOKRsp(pageInfo); }}Copy the code
3. Modify the CodeGenerator mentioned in the previous article as follows
package com.example.demo; import com.example.demo.core.constant.ProjectConstant; import com.google.common.base.CaseFormat; import freemarker.template.TemplateExceptionHandler; import org.apache.commons.lang3.StringUtils; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.*; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; /** * @author zhang Yao-@description: code generator, according to the data table name to generate the corresponding Model, Mapper, Service, Controller to simplify development. * @date 2018/4/23 20:28 */ public class CodeGenerator {// private static final String JDBC_URL ="jdbc:mysql://localhost:3333/demo";
private static final String JDBC_USERNAME = "root";
private static final String JDBC_PASSWORD = "123456";
private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; Private static final String TEMPLATE_FILE_PATH ="src/test/java/resources/template/generator";
private static final String JAVA_PATH = "src/main/java"; // Java file path private static final String RESOURCES_PATH ="src/main/resources"; // Resource file path // Generated Service path Private static final String PACKAGE_PATH_SERVICE = packageConvertPath(ProjectConstant.SERVICE_PACKAGE); // Generated Service implementation path Private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(ProjectConstant.SERVICE_IMPL_PACKAGE); // Generated Controller storage path Private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(ProjectConstant.CONTROLLER_PACKAGE); // @author private static final String AUTHOR ="Yiyad";
// @date
private static final String DATE = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new Date());
/**
* genCode("Enter table name");
* @param args
*/
public static void main(String[] args) {
genCode("system_log"); } /** * Generate code from the table name, the Model name is obtained by parsing the table name, underline to large hump form. For example, enter a table name"t_user_detail"Will generate * TUserDetail, TUserDetailMapper, TUserDetailService... * * @param tableNames table name... */ public static void genCode(String... tableNames) {for(String tableName : tableNames) { genCode(tableName); }} /** * Generate code from table names such as input table names"user_info"* UserInfo, UserInfoMapper, UserInfoService... * * @param tableName Name */ public static void genCode(String tableName) {genModelAndMapper(tableName); genService(tableName); genController(tableName); } public static void genModelAndMapper(String tableName) { Context context = getContext(); JDBCConnectionConfiguration jdbcConnectionConfiguration = getJDBCConnectionConfiguration(); context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration); PluginConfiguration pluginConfiguration = getPluginConfiguration(); context.addPluginConfiguration(pluginConfiguration); JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = getJavaModelGeneratorConfiguration(); context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration); SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = getSqlMapGeneratorConfiguration(); context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration); JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = getJavaClientGeneratorConfiguration(); context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration); TableConfiguration tableConfiguration = new TableConfiguration(context); tableConfiguration.setTableName(tableName); tableConfiguration.setDomainObjectName(null); context.addTableConfiguration(tableConfiguration); List<String> warnings; MyBatisGenerator generator; try { Configuration config = new Configuration(); config.addContext(context); config.validate(); boolean overwrite =true;
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
warnings = new ArrayList<>();
generator = new MyBatisGenerator(config, callback, warnings);
generator.generate(null);
} catch (Exception e) {
throw new RuntimeException("Failed to generate Model and Mapper", e);
}
if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
throw new RuntimeException(Failed to generate Model and Mapper: + warnings);
}
String modelName = tableNameConvertUpperCamel(tableName);
System.out.println(modelName + ".java generated successfully");
System.out.println(modelName + Mapper. Java generated successfully);
System.out.println(modelName + Mapper. XML generated successfully); } public static void genService(String tableName) { try { freemarker.template.Configuration cfg = getConfiguration(); Map<String, Object> data = new HashMap<>(); data.put("date", DATE);
data.put("author", AUTHOR);
String modelNameUpperCamel = tableNameConvertUpperCamel(tableName);
data.put("modelNameUpperCamel", modelNameUpperCamel);
data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
data.put("basePackage", ProjectConstant.BASE_PACKAGE);
data.put("basePackageService", ProjectConstant.SERVICE_PACKAGE);
data.put("basePackageServiceImpl", ProjectConstant.SERVICE_IMPL_PACKAGE);
data.put("basePackageModel", ProjectConstant.MODEL_PACKAGE);
data.put("basePackageDao", ProjectConstant.MAPPER_PACKAGE);
File file = new File(JAVA_PATH + PACKAGE_PATH_SERVICE + modelNameUpperCamel + "Service.java");
if(! file.getParentFile().exists()) { file.getParentFile().mkdirs(); } cfg.getTemplate("service.ftl").process(data, new FileWriter(file));
System.out.println(modelNameUpperCamel + "Service. Java generated successfully");
File file1 = new File(JAVA_PATH + PACKAGE_PATH_SERVICE_IMPL + modelNameUpperCamel + "ServiceImpl.java");
if(! file1.getParentFile().exists()) { file1.getParentFile().mkdirs(); } cfg.getTemplate("service-impl.ftl").process(data, new FileWriter(file1));
System.out.println(modelNameUpperCamel + "Serviceimp.java generated successfully");
} catch (Exception e) {
throw new RuntimeException("Failed to generate Service", e);
}
}
public static void genController(String tableName) {
try {
freemarker.template.Configuration cfg = getConfiguration();
Map<String, Object> data = new HashMap<>();
data.put("date", DATE);
data.put("author", AUTHOR);
String modelNameUpperCamel = tableNameConvertUpperCamel(tableName);
data.put("baseRequestMapping", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
data.put("modelNameUpperCamel", modelNameUpperCamel);
data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
data.put("basePackage", ProjectConstant.BASE_PACKAGE);
data.put("basePackageController", ProjectConstant.CONTROLLER_PACKAGE);
data.put("basePackageService", ProjectConstant.SERVICE_PACKAGE);
data.put("basePackageModel", ProjectConstant.MODEL_PACKAGE);
File file = new File(JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java");
if(! file.getParentFile().exists()) { file.getParentFile().mkdirs(); } cfg.getTemplate("controller.ftl").process(data, new FileWriter(file));
System.out.println(modelNameUpperCamel + "Controller. Java generated successfully");
} catch (Exception e) {
throw new RuntimeException("Failed to generate Controller", e);
}
}
private static Context getContext() {
Context context = new Context(ModelType.FLAT);
context.setId("Potato");
context.setTargetRuntime("MyBatis3Simple");
context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");
return context;
}
private static JDBCConnectionConfiguration getJDBCConnectionConfiguration() {
JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
return jdbcConnectionConfiguration;
}
private static PluginConfiguration getPluginConfiguration() {
PluginConfiguration pluginConfiguration = new PluginConfiguration();
pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
pluginConfiguration.addProperty("mappers", ProjectConstant.MAPPER_INTERFACE_REFERENCE);
return pluginConfiguration;
}
private static JavaModelGeneratorConfiguration getJavaModelGeneratorConfiguration() {
JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
javaModelGeneratorConfiguration.setTargetProject(JAVA_PATH);
javaModelGeneratorConfiguration.setTargetPackage(ProjectConstant.MODEL_PACKAGE);
javaModelGeneratorConfiguration.addProperty("enableSubPackages"."true");
javaModelGeneratorConfiguration.addProperty("trimStrings"."true");
return javaModelGeneratorConfiguration;
}
private static SqlMapGeneratorConfiguration getSqlMapGeneratorConfiguration() {
SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
sqlMapGeneratorConfiguration.setTargetProject(RESOURCES_PATH);
sqlMapGeneratorConfiguration.setTargetPackage("mapper");
return sqlMapGeneratorConfiguration;
}
private static JavaClientGeneratorConfiguration getJavaClientGeneratorConfiguration() {
JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
javaClientGeneratorConfiguration.setTargetProject(JAVA_PATH);
javaClientGeneratorConfiguration.setTargetPackage(ProjectConstant.MAPPER_PACKAGE);
javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
return javaClientGeneratorConfiguration;
}
private static freemarker.template.Configuration getConfiguration() throws IOException {
freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return cfg;
}
private static String tableNameConvertUpperCamel(String tableName) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());
}
private static String packageConvertPath(String packageName) {
return String.format("/%s/", packageName.contains(".")? packageName.replaceAll("\ \."."/") : packageName); }}Copy the code
Four: function test
Right-click Run in CodeGenerator
Ok, the creation is successful
The project address
Code cloud address: gitee.com/beany/mySpr…
GitHub address: github.com/MyBeany/myS…
Writing articles is not easy, if it is helpful to you, please help click star
At the end
Service, serviceImpl and Controller are automatically generated by freemarker. Subsequent functions will be updated in the future. If you have any questions, please contact me at [email protected]. Ask for directions from various gods, thank you.