废话不多说了,直接上代码
目录结构(红框中的文件为有用文件)
入库类
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 stub
if (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);//把组件添加到面板panel
panel.add(jTextField);
panel.add(label2);
panel.add(jTextField1);
panel.add(loginButton);
panel.add(exitButton);
frame.add(panel);//实现面板panel
frame.setVisible(true);//设置可见
}
public void actionPerformed(ActionEvent e) {//处理事件
}
@Autowired
static
FirstFrame 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.apache.commons.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() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return filePath + "/mapper/" + tableInfo.getEntityName() + StringPool.DOT_XML;
}
});
focList.add(new FileOutConfig("/templates/service.java.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义Server输入文件名称
return filePath + "/" + tableInfo.getEntityName() + "Service" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/controller.java.ftl") {
@Override
public 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.com.goldwind.ercp.fas.controller.FasWebBasePageController;
import cn.com.goldwind.ercp.common.persistence.entity.ReturnEntity;
import cn.com.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>
* ${table.comment!} 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 = "列分页查询")
@ResponseBody
public 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 = "新增")
@ResponseBody
public ReturnEntity add(@RequestBody ${entity} entity) {
service.add(entity);
return ReturnEntity.ok(CommonConstants.SUCCESS_MESSAGE);
}
@RequestMapping("edit")
@Log(operationType = "编辑", operationName = "编辑")
@ResponseBody
public ReturnEntity edit(@RequestBody ${entity} entity) {
service.edit(entity);
return ReturnEntity.ok(CommonConstants.SUCCESS_MESSAGE);
}
@RequestMapping("view")
@Log(operationType = "查看", operationName = "查看")
@ResponseBody
public ReturnEntity view(@RequestBody ${entity} entity) {
service.view(entity);
return ReturnEntity.ok(CommonConstants.SUCCESS_MESSAGE);
}
@RequestMapping("delete")
@Log(operationType = "删除", operationName = "删除")
@ResponseBody
public 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.com.goldwind.ercp.fas.service.impl.FasBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import cn.com.goldwind.springboot.framework.core.page.PagenationQueryParameter;
import javax.transaction.Transactional;
import cn.com.goldwind.ercp.auth.persistence.entity.SecUser;
import cn.com.goldwind.ercp.framework.kit.UUIDKit;
import java.util.*;
/**
* <p>
* ${table.comment!} 服务实现类
* </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 实体对象
*/
@Transactional
public 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 实体对象
*/
@Transactional
public 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 实体对象
*/
@Transactional
public List<${entity}> view(${entity} entity) {
return mapper.selectByPrimaryKey(entity.getId());
}
/**
* 逻辑删除
*
* @param entity 实体对象
*/
@Transactional
public 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>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>