mybatis 代码生成器,生成Controller和service

编程入门 行业动态 更新时间:2024-10-07 12:24:48

mybatis <a href=https://www.elefans.com/category/jswz/34/1766270.html style=代码生成器,生成Controller和service"/>

mybatis 代码生成器,生成Controller和service

废话不多说了,直接上代码

目录结构(红框中的文件为有用文件)

入库类

package com.wy;import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;import org.springframework.beans.factory.annotation.Autowired;public class main {static JPanel panel;static JLabel label,label2;static JButton loginButton,exitButton;static JTextField jTextField;static JTextField jTextField1;public static void startGenteratorFile() {JFrame frame = new JFrame();frame.setTitle("代码生成器");frame.setSize(250,220);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);panel = new JPanel();panel.setLayout(new FlowLayout());//设置为流式布局label = new JLabel("数据库表名");label2 = new JLabel("生成目录");loginButton = new JButton("生成");loginButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){// TODO Auto-generated method stubif (e.getSource()==loginButton) {String tableName = jTextField.getText();String filePath = jTextField1.getText();try {FirstFrame f = new FirstFrame(filePath);f.generatorFile(tableName);} catch (InterruptedException e1) {JOptionPane.showMessageDialog(null,"生成失败!" );}JOptionPane.showMessageDialog(null,"生成成功!" );}}});//监听事件exitButton = new JButton("退出");jTextField = new JTextField(16);//设置文本框的长度jTextField1 = new JTextField(16);//设置文本框的长度panel.add(label);//把组件添加到面板panelpanel.add(jTextField);panel.add(label2);panel.add(jTextField1);panel.add(loginButton);panel.add(exitButton);frame.add(panel);//实现面板panelframe.setVisible(true);//设置可见}public void actionPerformed(ActionEvent e) {//处理事件}@AutowiredstaticFirstFrame firstFrame = new FirstFrame();public static void main(String[] args) {startGenteratorFile();}
}

代码生成实现

package com.wy;import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;import org.apachemons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;import com.baomidou.mybatisplus.annotation.DbType;
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.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;@SuppressWarnings("serial")
public class FirstFrame {final String filePath;public FirstFrame(String filePath) {this.filePath = filePath;}public FirstFrame() {this.filePath = "";}public String getFilePath() {return filePath;}/*** 生成文件* * @param filePath  生成文件的目录* @param tableName 表名* @throws InterruptedException*/public void generatorFile(String tableName) throws InterruptedException {// 用来获取Mybatis-Plus.properties文件的配置信息final ResourceBundle rb = ResourceBundle.getBundle("mybatis-plus");// 代码生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();gc.setOutputDir(filePath);gc.setOpen(false);gc.setBaseResultMap(true);gc.setBaseColumnList(true);gc.setAuthor(rb.getString("author"));gc.setMapperName("%sMapper");gc.setXmlName("%sMapper");gc.setServiceName("%sService");gc.setServiceImplName("%sServiceImpl");gc.setControllerName("%sController");mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setDbType(DbType.POSTGRE_SQL);dsc.setUrl(rb.getString("url"));dsc.setDriverName(rb.getString("driver"));dsc.setUsername(rb.getString("userName"));dsc.setPassword(rb.getString("password"));mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setParent(rb.getString("parent"));pc.setController("controller");pc.setService("service");
//        pc.setServiceImpl("service.impl");
//        pc.setEntity("model");
//        pc.setMapper("mapper");mpg.setPackageInfo(pc);// 自定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};List<FileOutConfig> focList = new ArrayList<>();focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输入文件名称return filePath + "/mapper/" + tableInfo.getEntityName() + StringPool.DOT_XML;}});focList.add(new FileOutConfig("/templates/service.java.ftl") {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义Server输入文件名称return filePath + "/" + tableInfo.getEntityName() + "Service" + StringPool.DOT_JAVA;}});focList.add(new FileOutConfig("/templates/controller.java.ftl") {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义Controller输入文件名称return filePath + "/" + tableInfo.getEntityName() + "Controller" + StringPool.DOT_JAVA;}});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);mpg.setTemplate(new TemplateConfig().setXml(null));// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);strategy.setEntityLombokModel(true);strategy.setInclude(new String[] { tableName });strategy.setTablePrefix("my_");mpg.setStrategy(strategy);mpg.setTemplateEngine(new FreemarkerTemplateEngine());mpg.execute();// 只保留controller和service,其余删除delFile(filePath);}// 删除包含子文件夹和子文件的文件夹private static void delFile(String filePath) {File file = new File(filePath);File[] listFiles = file.listFiles();for (File i : listFiles) {if (i.isDirectory()) {deleteFile(i);}}}private static void deleteFile(File file) {if (file.isDirectory()) {File[] listFiles = file.listFiles();for (File i : listFiles) {deleteFile(i);}File[] listFiles1 = file.listFiles();if (listFiles1.length == 0) {file.delete();}} else {file.delete();}}}

介绍controller和service的模块代码(可根据自己的需求调整)

controller.java.ftl

package ${package.Controller};import ${package.Service}.${table.serviceName};
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import cn.goldwind.ercp.fas.controller.FasWebBasePageController;
import cn.goldwind.ercpmon.persistence.entity.ReturnEntity;
import cn.goldwind.ercp.annotation.Log;
import com.github.pagehelper.PageInfo;<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>/*** <p>* ${tablement!} controller管理层* </p>** @author ${author}* @since ${date}*/
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} extends FasWebBasePageController{
</#if>@Autowired${table.serviceName} service;@RequestMapping("query-page-list")@Log(operationType = "查询", operationName = "列分页查询")@ResponseBodypublic ReturnEntity queryPageList(@RequestBody ${entity} entity) {List<${entity}> listData = service.queryPageList(entity, buildPagenation());PageInfo<${entity}> pageInfo = new PageInfo<${entity}>(listData);return ReturnEntity.ok(pageInfo);}@RequestMapping("add")@Log(operationType = "新增", operationName = "新增")@ResponseBodypublic ReturnEntity add(@RequestBody ${entity} entity) {service.add(entity);return ReturnEntity.ok(CommonConstants.SUCCESS_MESSAGE);}@RequestMapping("edit")@Log(operationType = "编辑", operationName = "编辑")@ResponseBodypublic ReturnEntity edit(@RequestBody ${entity} entity) {service.edit(entity);return ReturnEntity.ok(CommonConstants.SUCCESS_MESSAGE);}@RequestMapping("view")@Log(operationType = "查看", operationName = "查看")@ResponseBodypublic ReturnEntity view(@RequestBody ${entity} entity) {service.view(entity);return ReturnEntity.ok(CommonConstants.SUCCESS_MESSAGE);}@RequestMapping("delete")@Log(operationType = "删除", operationName = "删除")@ResponseBodypublic ReturnEntity delete(@RequestBody ${entity} entity) {service.delete(entity);return ReturnEntity.ok(CommonConstants.SUCCESS_MESSAGE);}}
</#if>

service.java.ftl

package ${package.ServiceImpl};import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import org.springframework.stereotype.Service;
import cn.goldwind.ercp.fas.service.impl.FasBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import cn.goldwind.springboot.framework.core.page.PagenationQueryParameter;
import javax.transaction.Transactional;
import cn.goldwind.ercp.auth.persistence.entity.SecUser;
import cn.goldwind.ercp.framework.kit.UUIDKit;
import java.util.*;/*** <p>* ${tablement!} 服务实现类* </p>** @author ${author}* @since ${date}*/
@Service
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public class ${table.serviceName} extends FasBaseService  {@Autowired${table.mapperName} mapper;/*** 分页查询* @param entity* @param pageParam* @return*/public List<RegionEntity> queryPageList(${entity} entity, PagenationQueryParameter pageParam) {if (pageParam != null) {setPageHelper(pageParam);}return regionMapper.select(entity);}/*** 新增** @param entity 实体对象*/@Transactionalpublic int add(${entity} entity) {SecUser secUser = getLoginUser();entity.setId(UUIDKit.getUUID());entity.setCreateTime(new Date());entity.setDeleteFlg((short) 0);entity.setCreateUserId(secUser.getUserId());entity.setCreateUserName(secUser.getUserName());return mapper.insert(entity);}/*** 编辑** @param entity 实体对象*/@Transactionalpublic int edit(${entity} entity) {SecUser secUser = getLoginUser();entity.setUpdateTime(new Date());entity.setUpdateUserId(secUser.getUserId());entity.setUpdateUserName(secUser.getUserName());return mapper.updateByPrimaryKeySelective(entity);}/*** 查看** @param entity 实体对象*/@Transactionalpublic List<${entity}> view(${entity} entity) {return mapper.selectByPrimaryKey(entity.getId());}/*** 逻辑删除** @param entity 实体对象*/@Transactionalpublic int delete(${entity} entity) {SecUser secUser = getLoginUser();entity.setDeleteFlg((short) 1);entity.setUpdateTime(new Date());entity.setUpdateUserId(secUser.getUserId());entity.setUpdateUserName(secUser.getUserName());return mapper.updateByPrimaryKeySelective(entity);}
}
</#if>

mybatis-plus.properties

#此处为本项目src所在路径(代码生成器输出路径)
OutputDir=C:/Users/neusoft/Desktop/sqllist
#mapper.xml的生成位置
OutputDirXml=C:/Users/neusoft/Desktop/sqllist
#设置作者
author=wy
#自定义包路径
parent=
#数据库地址与yml配置的数据源地址一致
url=jdbc:postgresql://数据库地址?currentSchema=public
userName=账号
password=密码
driver=相应数据库驱动

pom.xml中需要添加的依赖

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.1.2</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.1.2</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.28</version></dependency><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.1</version></dependency><dependency><groupId>com.ibeetl</groupId><artifactId>beetl</artifactId><version>3.0.10.RELEASE</version></dependency><!-- .mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version></dependency>  

 

更多推荐

mybatis 代码生成器,生成Controller和service

本文发布于:2024-02-07 03:03:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1752977.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码生成器   mybatis   service   Controller

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!