├── README.md ├── src └── main │ ├── resources │ ├── application.properties │ ├── generator.yml │ ├── application-dev.properties │ ├── vm │ │ ├── java │ │ │ ├── Service.java.vm │ │ │ ├── Mapper.java.vm │ │ │ ├── domain.java.vm │ │ │ ├── ServiceImpl.java.vm │ │ │ └── Controller.java.vm │ │ ├── sql │ │ │ └── sql.vm │ │ ├── html │ │ │ ├── add.html.vm │ │ │ ├── edit.html.vm │ │ │ └── list.html.vm │ │ └── xml │ │ │ └── Mapper.xml.vm │ ├── mapper │ │ └── generate │ │ │ └── GenMapper.xml │ └── templates │ │ └── tool │ │ └── gen │ │ └── gen.html │ └── java │ └── com │ └── sue │ └── generate │ ├── Application.java │ ├── util │ ├── VelocityInitializer.java │ ├── CharsetKit.java │ ├── StrFormatter.java │ ├── GenUtils.java │ ├── StringUtils.java │ └── Convert.java │ ├── service │ ├── IGenService.java │ └── impl │ │ └── GenServiceImpl.java │ ├── mapper │ └── GenMapper.java │ ├── domain │ ├── ColumnConfigInfo.java │ ├── BaseEntity.java │ ├── TableInfo.java │ └── ColumnInfo.java │ ├── config │ └── GenConfig.java │ └── controller │ └── GenController.java ├── .gitignore └── pom.xml /README.md: -------------------------------------------------------------------------------- 1 | # code-generate 2 | 代码生成工具 3 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=dev -------------------------------------------------------------------------------- /src/main/resources/generator.yml: -------------------------------------------------------------------------------- 1 | 2 | # 代码生成 3 | gen: 4 | # 作者 5 | author: sue 6 | # 默认生成包路径 system 需改成自己的模块名称 如 system monitor tool 7 | packageName: com.sue 8 | # 自动去除表前缀,默认是true 9 | autoRemovePre: true 10 | # 表前缀(类名不会包含表前缀) 11 | tablePrefix: sys_ -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | *.log 5 | *.dat 6 | .DS_Store 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | 15 | ### IntelliJ IDEA ### 16 | .idea 17 | *.iws 18 | *.iml 19 | *.ipr 20 | 21 | ### NetBeans ### 22 | nbproject/private/ 23 | build/ 24 | nbbuild/ 25 | dist/ 26 | lib/ 27 | nbdist/ 28 | .nb-gradle/ 29 | 30 | node_modules/ 31 | npm-debug.log* 32 | yarn-debug.log* 33 | yarn-error.log* 34 | test/unit/coverage 35 | 36 | # Editor directories and files 37 | *.suo 38 | *.ntvs* 39 | *.njsproj 40 | *.sln 41 | 42 | filer/ 43 | /framework-lte-*.tgz 44 | 45 | /logs 46 | /.vs -------------------------------------------------------------------------------- /src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | spring.application.name = code-generate 2 | server.port = 8081 3 | 4 | spring.datasource.type=com.alibaba.druid.pool.DruidDataSource 5 | spring.datasource.driverClassName=com.mysql.jdbc.Driver 6 | spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8 7 | spring.datasource.username=root 8 | spring.datasource.password=123456 9 | mapper.identity=MYSQL 10 | mapper.before=false 11 | 12 | 13 | #加载Mybatis配置文件 14 | logging.level.com.sue.generate.mapper.**=debug 15 | mybatis.mapper-locations = classpath:mapper/generate/*Mapper.xml 16 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/Application.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.WebApplicationType; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.builder.SpringApplicationBuilder; 7 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 8 | 9 | /** 10 | * 服务启动程序 11 | * 12 | * @author : sue 13 | */ 14 | @EnableSwagger2 15 | @MapperScan(basePackages = {"com.sue.generate.mapper"}) 16 | @SpringBootApplication 17 | public class Application { 18 | 19 | /** 20 | * 程序入口 21 | * 22 | * @param args 程序输入参数 23 | */ 24 | public static void main(String[] args) { 25 | new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/util/VelocityInitializer.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.util; 2 | 3 | import java.util.Properties; 4 | 5 | import org.apache.velocity.app.Velocity; 6 | 7 | /** 8 | * VelocityEngine工厂 9 | * 10 | * @author sue 11 | */ 12 | public class VelocityInitializer { 13 | 14 | private final static String UTF8 = "UTF8"; 15 | 16 | /** 17 | * 初始化vm方法 18 | */ 19 | public static void initVelocity() { 20 | Properties p = new Properties(); 21 | try { 22 | // 加载classpath目录下的vm文件 23 | p.setProperty("file.resource.loader.class", 24 | "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); 25 | // 定义字符集 26 | p.setProperty(Velocity.ENCODING_DEFAULT, UTF8); 27 | p.setProperty(Velocity.OUTPUT_ENCODING, UTF8); 28 | // 初始化Velocity引擎,指定配置Properties 29 | Velocity.init(p); 30 | } catch (Exception e) { 31 | throw new RuntimeException(e); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/service/IGenService.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.service; 2 | 3 | import java.util.List; 4 | 5 | import com.sue.generate.domain.TableInfo; 6 | 7 | /** 8 | * 代码生成 服务层 9 | * 10 | * @author sue 11 | */ 12 | public interface IGenService { 13 | /** 14 | * 查询ry数据库表信息 15 | * 16 | * @param tableInfo 表信息 17 | * @return 数据库表列表 18 | */ 19 | List selectTableList(TableInfo tableInfo); 20 | 21 | /** 22 | * 生成代码 23 | * 24 | * @param author 作者 25 | * @param packageName 包名称 26 | * @param dataBaseName 库名称 27 | * @param tableName 表名称 28 | * @return 数据 29 | */ 30 | byte[] generatorCode(String author, String packageName, String dataBaseName, String tableName); 31 | 32 | /** 33 | * 批量生成代码 34 | * 35 | * @param author 作者 36 | * @param packageName 包名称 37 | * @param dataBaseName 库名称 38 | * @param tableNames 表数组 39 | * @return 数据 40 | */ 41 | byte[] generatorCode(String author, String packageName, String dataBaseName, String[] tableNames); 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/mapper/GenMapper.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.mapper; 2 | 3 | import java.util.List; 4 | 5 | import com.sue.generate.domain.ColumnInfo; 6 | import com.sue.generate.domain.TableInfo; 7 | import org.apache.ibatis.annotations.Param; 8 | import org.springframework.stereotype.Component; 9 | 10 | /** 11 | * 代码生成 数据层 12 | * 13 | * @author sue 14 | */ 15 | @Component 16 | public interface GenMapper { 17 | /** 18 | * 查询ry数据库表信息 19 | * 20 | * @param tableInfo 表信息 21 | * @return 数据库表列表 22 | */ 23 | List selectTableList(TableInfo tableInfo); 24 | 25 | /** 26 | * 根据表名称查询信息 27 | * 28 | * @param dataBaseName 库名称 29 | * @param tableName 表名称 30 | * @return 表信息 31 | */ 32 | TableInfo selectTableByName(@Param("dataBaseName") String dataBaseName, @Param("tableName") String tableName); 33 | 34 | /** 35 | * 根据表名称查询列信息 36 | * 37 | * @param dataBaseName 库名称 38 | * @param tableName 表名称 39 | * @return 列信息 40 | */ 41 | List selectTableColumnsByName(@Param("dataBaseName") String dataBaseName, @Param("tableName") String tableName); 42 | } 43 | -------------------------------------------------------------------------------- /src/main/resources/vm/java/Service.java.vm: -------------------------------------------------------------------------------- 1 | package ${package}.service; 2 | 3 | import ${package}.domain.${className}; 4 | import java.util.List; 5 | 6 | /** 7 | * ${tableComment} 服务层 8 | * 9 | * @author ${author} 10 | * @date ${datetime} 11 | */ 12 | public interface I${className}Service 13 | { 14 | /** 15 | * 查询${tableComment}信息 16 | * 17 | * @param ${primaryKey.attrname} ${tableComment}ID 18 | * @return ${tableComment}信息 19 | */ 20 | public ${className} select${className}ById(${primaryKey.attrType} ${primaryKey.attrname}); 21 | 22 | /** 23 | * 查询${tableComment}列表 24 | * 25 | * @param ${classname} ${tableComment}信息 26 | * @return ${tableComment}集合 27 | */ 28 | public List<${className}> select${className}List(${className} ${classname}); 29 | 30 | /** 31 | * 新增${tableComment} 32 | * 33 | * @param ${classname} ${tableComment}信息 34 | * @return 结果 35 | */ 36 | public int insert${className}(${className} ${classname}); 37 | 38 | /** 39 | * 修改${tableComment} 40 | * 41 | * @param ${classname} ${tableComment}信息 42 | * @return 结果 43 | */ 44 | public int update${className}(${className} ${classname}); 45 | 46 | /** 47 | * 删除${tableComment}信息 48 | * 49 | * @param ids 需要删除的数据ID 50 | * @return 结果 51 | */ 52 | public int delete${className}ByIds(String ids); 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/domain/ColumnConfigInfo.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.domain; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | /** 6 | * 字段类型配置 由数据库字段的注释解析而来 7 | * 注释结构示例:{"title": "状态", "type": "dict", "value": "sys_common_status"} {"title": "登录时间", "type": "date"} 8 | * 9 | * @author sue 10 | */ 11 | @JsonIgnoreProperties(ignoreUnknown = true) 12 | public class ColumnConfigInfo { 13 | /** 14 | * 属性标题 15 | */ 16 | private String title; 17 | 18 | /** 19 | * 属性类型 dict(字典,value对应字典管理的字典类型), date(包括date) 20 | */ 21 | private String type; 22 | 23 | /** 24 | * 属性值,参考数据类型,可为空 25 | */ 26 | private String value; 27 | 28 | public ColumnConfigInfo() { 29 | super(); 30 | } 31 | 32 | public ColumnConfigInfo(String title, String type, String value) { 33 | super(); 34 | this.title = title; 35 | this.type = type; 36 | this.value = value; 37 | } 38 | 39 | public String getTitle() { 40 | return title; 41 | } 42 | 43 | public void setTitle(String title) { 44 | this.title = title; 45 | } 46 | 47 | public String getType() { 48 | return type; 49 | } 50 | 51 | public void setType(String type) { 52 | this.type = type; 53 | } 54 | 55 | public String getValue() { 56 | return value; 57 | } 58 | 59 | public void setValue(String value) { 60 | this.value = value; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/domain/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.domain; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFormat; 4 | 5 | import java.io.Serializable; 6 | import java.util.Date; 7 | 8 | /** 9 | * Entity基类 10 | * 11 | * @author sue 12 | */ 13 | public class BaseEntity implements Serializable { 14 | private static final long serialVersionUID = 1L; 15 | 16 | 17 | /** 18 | * 创建者 19 | */ 20 | private String createBy; 21 | 22 | /** 23 | * 创建时间 24 | */ 25 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 26 | private Date createTime; 27 | 28 | /** 29 | * 更新者 30 | */ 31 | private String updateBy; 32 | 33 | /** 34 | * 更新时间 35 | */ 36 | @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 37 | private Date updateTime; 38 | 39 | 40 | public String getCreateBy() { 41 | return createBy; 42 | } 43 | 44 | public void setCreateBy(String createBy) { 45 | this.createBy = createBy; 46 | } 47 | 48 | public Date getCreateTime() { 49 | return createTime; 50 | } 51 | 52 | public void setCreateTime(Date createTime) { 53 | this.createTime = createTime; 54 | } 55 | 56 | public String getUpdateBy() { 57 | return updateBy; 58 | } 59 | 60 | public void setUpdateBy(String updateBy) { 61 | this.updateBy = updateBy; 62 | } 63 | 64 | public Date getUpdateTime() { 65 | return updateTime; 66 | } 67 | 68 | public void setUpdateTime(Date updateTime) { 69 | this.updateTime = updateTime; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/resources/vm/sql/sql.vm: -------------------------------------------------------------------------------- 1 | -- 菜单 SQL 2 | insert into sys_menu (menu_name, parent_id, order_num, url,menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark) 3 | values('${tableComment}', '3', '1', '/${moduleName}/${classname}', 'C', '0', '${moduleName}:${classname}:view', '#', 'admin', '2018-03-01', 'ry', '2018-03-01', '${tableComment}菜单'); 4 | 5 | -- 按钮父菜单ID 6 | SELECT @parentId := LAST_INSERT_ID(); 7 | 8 | -- 按钮 SQL 9 | insert into sys_menu (menu_name, parent_id, order_num, url,menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark) 10 | values('${tableComment}查询', @parentId, '1', '#', 'F', '0', '${moduleName}:${classname}:list', '#', 'admin', '2018-03-01', 'ry', '2018-03-01', ''); 11 | 12 | insert into sys_menu (menu_name, parent_id, order_num, url,menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark) 13 | values('${tableComment}新增', @parentId, '2', '#', 'F', '0', '${moduleName}:${classname}:add', '#', 'admin', '2018-03-01', 'ry', '2018-03-01', ''); 14 | 15 | insert into sys_menu (menu_name, parent_id, order_num, url,menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark) 16 | values('${tableComment}修改', @parentId, '3', '#', 'F', '0', '${moduleName}:${classname}:edit', '#', 'admin', '2018-03-01', 'ry', '2018-03-01', ''); 17 | 18 | insert into sys_menu (menu_name, parent_id, order_num, url,menu_type, visible, perms, icon, create_by, create_time, update_by, update_time, remark) 19 | values('${tableComment}删除', @parentId, '4', '#', 'F', '0', '${moduleName}:${classname}:remove', '#', 'admin', '2018-03-01', 'ry', '2018-03-01', ''); 20 | -------------------------------------------------------------------------------- /src/main/resources/vm/java/Mapper.java.vm: -------------------------------------------------------------------------------- 1 | package ${package}.mapper; 2 | 3 | import ${package}.domain.${className}; 4 | import java.util.List; 5 | 6 | /** 7 | * ${tableComment} 数据层 8 | * 9 | * @author ${author} 10 | * @date ${datetime} 11 | */ 12 | public interface ${className}Mapper 13 | { 14 | /** 15 | * 查询${tableComment}信息 16 | * 17 | * @param ${primaryKey.attrname} ${tableComment}ID 18 | * @return ${tableComment}信息 19 | */ 20 | public ${className} select${className}ById(${primaryKey.attrType} ${primaryKey.attrname}); 21 | 22 | /** 23 | * 查询${tableComment}列表 24 | * 25 | * @param ${classname} ${tableComment}信息 26 | * @return ${tableComment}集合 27 | */ 28 | public List<${className}> select${className}List(${className} ${classname}); 29 | 30 | /** 31 | * 新增${tableComment} 32 | * 33 | * @param ${classname} ${tableComment}信息 34 | * @return 结果 35 | */ 36 | public int insert${className}(${className} ${classname}); 37 | 38 | /** 39 | * 修改${tableComment} 40 | * 41 | * @param ${classname} ${tableComment}信息 42 | * @return 结果 43 | */ 44 | public int update${className}(${className} ${classname}); 45 | 46 | /** 47 | * 删除${tableComment} 48 | * 49 | * @param ${primaryKey.attrname} ${tableComment}ID 50 | * @return 结果 51 | */ 52 | public int delete${className}ById(${primaryKey.attrType} ${primaryKey.attrname}); 53 | 54 | /** 55 | * 批量删除${tableComment} 56 | * 57 | * @param ${primaryKey.attrname}s 需要删除的数据ID 58 | * @return 结果 59 | */ 60 | public int delete${className}ByIds(String[] ${primaryKey.attrname}s); 61 | 62 | } -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/config/GenConfig.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.context.annotation.PropertySource; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * 读取代码生成相关配置 10 | * 11 | * @author sue 12 | */ 13 | @Component 14 | @ConfigurationProperties(prefix = "gen") 15 | @PropertySource(value = {"classpath:generator.yml"}) 16 | public class GenConfig { 17 | /** 18 | * 作者 19 | */ 20 | public static String author; 21 | 22 | /** 23 | * 生成包路径 24 | */ 25 | public static String packageName; 26 | 27 | /** 28 | * 自动去除表前缀,默认是true 29 | */ 30 | public static String autoRemovePre; 31 | 32 | /** 33 | * 表前缀(类名不会包含表前缀) 34 | */ 35 | public static String tablePrefix; 36 | 37 | public static String getAuthor() { 38 | return author; 39 | } 40 | 41 | @Value("${author}") 42 | public void setAuthor(String author) { 43 | GenConfig.author = author; 44 | } 45 | 46 | public static String getPackageName() { 47 | return packageName; 48 | } 49 | 50 | @Value("${packageName}") 51 | public void setPackageName(String packageName) { 52 | GenConfig.packageName = packageName; 53 | } 54 | 55 | public static String getAutoRemovePre() { 56 | return autoRemovePre; 57 | } 58 | 59 | @Value("${autoRemovePre}") 60 | public void setAutoRemovePre(String autoRemovePre) { 61 | GenConfig.autoRemovePre = autoRemovePre; 62 | } 63 | 64 | public static String getTablePrefix() { 65 | return tablePrefix; 66 | } 67 | 68 | @Value("${tablePrefix}") 69 | public void setTablePrefix(String tablePrefix) { 70 | GenConfig.tablePrefix = tablePrefix; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/resources/vm/java/domain.java.vm: -------------------------------------------------------------------------------- 1 | package ${package}.domain; 2 | 3 | import org.apache.commons.lang3.builder.ToStringBuilder; 4 | import org.apache.commons.lang3.builder.ToStringStyle; 5 | import com.sue.common.core.domain.BaseEntity; 6 | #foreach ($column in $columns) 7 | #if($column.attrType == 'Date' && ($column.attrname != 'createBy' && $column.attrname != 'createTime' && $column.attrname != 'updateBy' && $column.attrname != 'updateTime' && $column.attrname != 'remark')) 8 | import java.util.Date; 9 | #break 10 | #end 11 | #end 12 | #foreach ($column in $columns) 13 | #if($column.attrType == 'BigDecimal') 14 | import java.math.BigDecimal; 15 | #break 16 | #end 17 | #end 18 | 19 | /** 20 | * ${tableComment}表 ${tableName} 21 | * 22 | * @author ${author} 23 | * @date ${datetime} 24 | */ 25 | public class ${className} extends BaseEntity 26 | { 27 | private static final long serialVersionUID = 1L; 28 | 29 | #foreach ($column in $columns) 30 | #if($column.attrname != 'createBy' && $column.attrname != 'createTime' && $column.attrname != 'updateBy' && $column.attrname != 'updateTime' && $column.attrname != 'remark') 31 | /** $column.columnComment */ 32 | private $column.attrType $column.attrname; 33 | #end 34 | #end 35 | 36 | #foreach ($column in $columns) 37 | #if($column.attrname != 'createBy' && $column.attrname != 'createTime' && $column.attrname != 'updateBy' && $column.attrname != 'updateTime' && $column.attrname != 'remark') 38 | public void set${column.attrName}($column.attrType $column.attrname) 39 | { 40 | this.$column.attrname = $column.attrname; 41 | } 42 | 43 | public $column.attrType get${column.attrName}() 44 | { 45 | return $column.attrname; 46 | } 47 | #end 48 | #end 49 | 50 | public String toString() { 51 | return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) 52 | #foreach ($column in $columns) 53 | .append("${column.attrname}", get${column.attrName}()) 54 | #end 55 | .toString(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/controller/GenController.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.controller; 2 | 3 | import java.io.IOException; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | import io.swagger.annotations.Api; 7 | import io.swagger.annotations.ApiOperation; 8 | import org.apache.commons.io.IOUtils; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import com.sue.generate.service.IGenService; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | /** 17 | * 代码生成 操作处理 18 | * 19 | * @author sue 20 | */ 21 | @Api(tags = "tool" , description = "代码生成工具") 22 | @RestController 23 | @RequestMapping("/tool/gen") 24 | public class GenController { 25 | 26 | @Autowired 27 | private IGenService genService; 28 | 29 | 30 | /** 31 | * 生成代码 32 | */ 33 | @ApiOperation(notes = "多表代码生成接口" , value = "") 34 | @GetMapping("/genCode/{author}/{packageName}/{dataBaseName}/{tableName}") 35 | public void genCode(HttpServletResponse response, 36 | @PathVariable("author") String author, 37 | @PathVariable("packageName") String packageName, 38 | @PathVariable("dataBaseName") String dataBaseName, 39 | @PathVariable("tableName") String tableName) throws IOException { 40 | byte[] data = genService.generatorCode(author, packageName, dataBaseName, tableName); 41 | genCode(response, data); 42 | } 43 | 44 | /** 45 | * 生成zip文件 46 | * 47 | * @param response 48 | * @param data 49 | * @throws IOException 50 | */ 51 | private void genCode(HttpServletResponse response, byte[] data) throws IOException { 52 | response.reset(); 53 | response.setHeader("Content-Disposition", "attachment; filename=\"sue.zip\""); 54 | response.addHeader("Content-Length", "" + data.length); 55 | response.setContentType("application/octet-stream; charset=UTF-8"); 56 | IOUtils.write(data, response.getOutputStream()); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/resources/vm/html/add.html.vm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | #foreach($column in $columns) 10 | #if($column.columnName != $primaryKey.columnName) 11 | #if(!${column.configInfo}) 12 |
13 | 14 |
15 | 16 |
17 |
18 | #else 19 | #if(${column.configInfo.type} == "dict") 20 |
21 | 22 |
23 | 26 |
27 |
28 | #elseif(${column.configInfo.type} == "date") 29 |
30 | 31 |
32 | 33 |
34 |
35 | #elseif(${column.configInfo.type} == "fk") 36 | #end 37 | #end 38 | #end 39 | #end 40 |
41 |
42 |
43 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/main/resources/vm/java/ServiceImpl.java.vm: -------------------------------------------------------------------------------- 1 | package ${package}.service.impl; 2 | 3 | import java.util.List; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Service; 6 | import ${package}.mapper.${className}Mapper; 7 | import ${package}.domain.${className}; 8 | import ${package}.service.I${className}Service; 9 | import com.sue.common.core.text.Convert; 10 | 11 | /** 12 | * ${tableComment} 服务层实现 13 | * 14 | * @author ${author} 15 | * @date ${datetime} 16 | */ 17 | @Service 18 | public class ${className}ServiceImpl implements I${className}Service 19 | { 20 | @Autowired 21 | private ${className}Mapper ${classname}Mapper; 22 | 23 | /** 24 | * 查询${tableComment}信息 25 | * 26 | * @param ${primaryKey.attrname} ${tableComment}ID 27 | * @return ${tableComment}信息 28 | */ 29 | @Override 30 | public ${className} select${className}ById(${primaryKey.attrType} ${primaryKey.attrname}) 31 | { 32 | return ${classname}Mapper.select${className}ById(${primaryKey.attrname}); 33 | } 34 | 35 | /** 36 | * 查询${tableComment}列表 37 | * 38 | * @param ${classname} ${tableComment}信息 39 | * @return ${tableComment}集合 40 | */ 41 | @Override 42 | public List<${className}> select${className}List(${className} ${classname}) 43 | { 44 | return ${classname}Mapper.select${className}List(${classname}); 45 | } 46 | 47 | /** 48 | * 新增${tableComment} 49 | * 50 | * @param ${classname} ${tableComment}信息 51 | * @return 结果 52 | */ 53 | @Override 54 | public int insert${className}(${className} ${classname}) 55 | { 56 | return ${classname}Mapper.insert${className}(${classname}); 57 | } 58 | 59 | /** 60 | * 修改${tableComment} 61 | * 62 | * @param ${classname} ${tableComment}信息 63 | * @return 结果 64 | */ 65 | @Override 66 | public int update${className}(${className} ${classname}) 67 | { 68 | return ${classname}Mapper.update${className}(${classname}); 69 | } 70 | 71 | /** 72 | * 删除${tableComment}对象 73 | * 74 | * @param ids 需要删除的数据ID 75 | * @return 结果 76 | */ 77 | @Override 78 | public int delete${className}ByIds(String ids) 79 | { 80 | return ${classname}Mapper.delete${className}ByIds(Convert.toStrArray(ids)); 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/resources/mapper/generate/GenMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | select table_name, table_comment, create_time, update_time from information_schema.tables 22 | 23 | 24 | 40 | 41 | 46 | 47 | 51 | 52 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/domain/TableInfo.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.domain; 2 | 3 | import java.util.List; 4 | 5 | import com.sue.generate.util.StringUtils; 6 | 7 | /** 8 | * ry 数据库表 9 | * 10 | * @author sue 11 | */ 12 | public class TableInfo extends BaseEntity { 13 | private static final long serialVersionUID = 1L; 14 | 15 | /** 16 | * 表名称 17 | */ 18 | private String tableName; 19 | 20 | /** 21 | * 表描述 22 | */ 23 | private String tableComment; 24 | 25 | /** 26 | * 表的主键列信息 27 | */ 28 | private ColumnInfo primaryKey; 29 | 30 | /** 31 | * 表的列名(不包含主键) 32 | */ 33 | private List columns; 34 | 35 | /** 36 | * 类名(第一个字母大写) 37 | */ 38 | private String className; 39 | 40 | /** 41 | * 类名(第一个字母小写) 42 | */ 43 | private String classname; 44 | 45 | public String getTableName() { 46 | return tableName; 47 | } 48 | 49 | public void setTableName(String tableName) { 50 | this.tableName = tableName; 51 | } 52 | 53 | public String getTableComment() { 54 | return tableComment; 55 | } 56 | 57 | public void setTableComment(String tableComment) { 58 | this.tableComment = tableComment; 59 | } 60 | 61 | public List getColumns() { 62 | return columns; 63 | } 64 | 65 | public ColumnInfo getColumnsLast() { 66 | ColumnInfo columnInfo = null; 67 | if (StringUtils.isNotNull(columns) && columns.size() > 0) { 68 | columnInfo = columns.get(0); 69 | } 70 | return columnInfo; 71 | } 72 | 73 | public void setColumns(List columns) { 74 | this.columns = columns; 75 | } 76 | 77 | public String getClassName() { 78 | return className; 79 | } 80 | 81 | public void setClassName(String className) { 82 | this.className = className; 83 | } 84 | 85 | public String getClassname() { 86 | return classname; 87 | } 88 | 89 | public void setClassname(String classname) { 90 | this.classname = classname; 91 | } 92 | 93 | public ColumnInfo getPrimaryKey() { 94 | return primaryKey; 95 | } 96 | 97 | public void setPrimaryKey(ColumnInfo primaryKey) { 98 | this.primaryKey = primaryKey; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/resources/vm/html/edit.html.vm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | #foreach($column in $columns) 11 | #if($column.columnName != $primaryKey.columnName) 12 | #if(!${column.configInfo}) 13 |
14 | 15 |
16 | 17 |
18 |
19 | #else 20 | #if(${column.configInfo.type} == "dict") 21 |
22 | 23 |
24 | 27 |
28 |
29 | #elseif(${column.configInfo.type} == "date") 30 |
31 | 32 |
33 | 34 |
35 |
36 | #elseif(${column.configInfo.type} == "fk") 37 | #end 38 | #end 39 | #end 40 | #end 41 |
42 |
43 |
44 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/util/CharsetKit.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.util; 2 | 3 | import java.nio.charset.Charset; 4 | import java.nio.charset.StandardCharsets; 5 | 6 | /** 7 | * 字符集工具类 8 | * 9 | * @author sue 10 | */ 11 | public class CharsetKit { 12 | /** 13 | * ISO-8859-1 14 | */ 15 | public static final String ISO_8859_1 = "ISO-8859-1"; 16 | /** 17 | * UTF-8 18 | */ 19 | public static final String UTF_8 = "UTF-8"; 20 | /** 21 | * GBK 22 | */ 23 | public static final String GBK = "GBK"; 24 | 25 | /** 26 | * ISO-8859-1 27 | */ 28 | public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1); 29 | /** 30 | * UTF-8 31 | */ 32 | public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8); 33 | /** 34 | * GBK 35 | */ 36 | public static final Charset CHARSET_GBK = Charset.forName(GBK); 37 | 38 | /** 39 | * 转换为Charset对象 40 | * 41 | * @param charset 字符集,为空则返回默认字符集 42 | * @return Charset 43 | */ 44 | public static Charset charset(String charset) { 45 | return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset); 46 | } 47 | 48 | /** 49 | * 转换字符串的字符集编码 50 | * 51 | * @param source 字符串 52 | * @param srcCharset 源字符集,默认ISO-8859-1 53 | * @param destCharset 目标字符集,默认UTF-8 54 | * @return 转换后的字符集 55 | */ 56 | public static String convert(String source, String srcCharset, String destCharset) { 57 | return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); 58 | } 59 | 60 | /** 61 | * 转换字符串的字符集编码 62 | * 63 | * @param source 字符串 64 | * @param srcCharset 源字符集,默认ISO-8859-1 65 | * @param destCharset 目标字符集,默认UTF-8 66 | * @return 转换后的字符集 67 | */ 68 | public static String convert(String source, Charset srcCharset, Charset destCharset) { 69 | if (null == srcCharset) { 70 | srcCharset = StandardCharsets.ISO_8859_1; 71 | } 72 | 73 | if (null == destCharset) { 74 | srcCharset = StandardCharsets.UTF_8; 75 | } 76 | 77 | if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) { 78 | return source; 79 | } 80 | return new String(source.getBytes(srcCharset), destCharset); 81 | } 82 | 83 | /** 84 | * @return 系统字符集编码 85 | */ 86 | public static String systemCharset() { 87 | return Charset.defaultCharset().name(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/domain/ColumnInfo.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.domain; 2 | 3 | 4 | /** 5 | * ry数据库表列信息 6 | * 7 | * @author sue 8 | */ 9 | public class ColumnInfo { 10 | /** 11 | * 字段名称 12 | */ 13 | private String columnName; 14 | 15 | /** 16 | * 字段类型 17 | */ 18 | private String dataType; 19 | 20 | /** 21 | * 列描述 22 | */ 23 | private String columnComment; 24 | 25 | /** 26 | * 列配置 27 | */ 28 | private ColumnConfigInfo configInfo; 29 | 30 | /** 31 | * Java属性类型 32 | */ 33 | private String attrType; 34 | 35 | /** 36 | * Java属性名称(第一个字母大写),如:user_name => UserName 37 | */ 38 | private String attrName; 39 | 40 | /** 41 | * Java属性名称(第一个字母小写),如:user_name => userName 42 | */ 43 | private String attrname; 44 | 45 | /** 46 | * 执行计划(包含了与索引相关的一些细节信息) 47 | */ 48 | private String extra; 49 | 50 | public String getColumnName() { 51 | return columnName; 52 | } 53 | 54 | public void setColumnName(String columnName) { 55 | this.columnName = columnName; 56 | } 57 | 58 | public String getDataType() { 59 | return dataType; 60 | } 61 | 62 | public void setDataType(String dataType) { 63 | this.dataType = dataType; 64 | } 65 | 66 | public String getColumnComment() { 67 | return columnComment; 68 | } 69 | 70 | public void setColumnComment(String columnComment) throws Exception { 71 | this.columnComment = columnComment; 72 | } 73 | 74 | public String getAttrName() { 75 | return attrName; 76 | } 77 | 78 | public void setAttrName(String attrName) { 79 | this.attrName = attrName; 80 | } 81 | 82 | public String getAttrname() { 83 | return attrname; 84 | } 85 | 86 | public void setAttrname(String attrname) { 87 | this.attrname = attrname; 88 | } 89 | 90 | public String getAttrType() { 91 | return attrType; 92 | } 93 | 94 | public void setAttrType(String attrType) { 95 | this.attrType = attrType; 96 | } 97 | 98 | public String getExtra() { 99 | return extra; 100 | } 101 | 102 | public void setExtra(String extra) { 103 | this.extra = extra; 104 | } 105 | 106 | public ColumnConfigInfo getConfigInfo() { 107 | return configInfo; 108 | } 109 | 110 | public void setConfigInfo(ColumnConfigInfo configInfo) { 111 | this.configInfo = configInfo; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/util/StrFormatter.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.util; 2 | 3 | /** 4 | * 字符串格式化 5 | * 6 | * @author sue 7 | */ 8 | public class StrFormatter { 9 | public static final String EMPTY_JSON = "{}"; 10 | public static final char C_BACKSLASH = '\\'; 11 | public static final char C_DELIM_START = '{'; 12 | public static final char C_DELIM_END = '}'; 13 | 14 | /** 15 | * 格式化字符串
16 | * 此方法只是简单将占位符 {} 按照顺序替换为参数
17 | * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
18 | * 例:
19 | * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
20 | * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
21 | * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
22 | * 23 | * @param strPattern 字符串模板 24 | * @param argArray 参数列表 25 | * @return 结果 26 | */ 27 | public static String format(final String strPattern, final Object... argArray) { 28 | if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray)) { 29 | return strPattern; 30 | } 31 | final int strPatternLength = strPattern.length(); 32 | 33 | // 初始化定义好的长度以获得更好的性能 34 | StringBuilder sbuf = new StringBuilder(strPatternLength + 50); 35 | 36 | int handledPosition = 0; 37 | int delimIndex;// 占位符所在位置 38 | for (int argIndex = 0; argIndex < argArray.length; argIndex++) { 39 | delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition); 40 | if (delimIndex == -1) { 41 | if (handledPosition == 0) { 42 | return strPattern; 43 | } else { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果 44 | sbuf.append(strPattern, handledPosition, strPatternLength); 45 | return sbuf.toString(); 46 | } 47 | } else { 48 | if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) { 49 | if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) { 50 | // 转义符之前还有一个转义符,占位符依旧有效 51 | sbuf.append(strPattern, handledPosition, delimIndex - 1); 52 | sbuf.append(Convert.utf8Str(argArray[argIndex])); 53 | handledPosition = delimIndex + 2; 54 | } else { 55 | // 占位符被转义 56 | argIndex--; 57 | sbuf.append(strPattern, handledPosition, delimIndex - 1); 58 | sbuf.append(C_DELIM_START); 59 | handledPosition = delimIndex + 1; 60 | } 61 | } else { 62 | // 正常占位符 63 | sbuf.append(strPattern, handledPosition, delimIndex); 64 | sbuf.append(Convert.utf8Str(argArray[argIndex])); 65 | handledPosition = delimIndex + 2; 66 | } 67 | } 68 | } 69 | // 加入最后一个占位符后所有的字符 70 | sbuf.append(strPattern, handledPosition, strPattern.length()); 71 | 72 | return sbuf.toString(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/resources/vm/xml/Mapper.xml.vm: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | #foreach ($column in $columns) 9 | 10 | #end 11 | 12 | 13 | 14 | select#foreach($column in $columns) $column.columnName#if($velocityCount != $columns.size()),#end#end from ${tableName} 15 | 16 | 17 | 25 | 26 | 30 | 31 | 32 | insert into ${tableName} 33 | 34 | #foreach($column in $columns) 35 | #if($column.columnName != $primaryKey.columnName || $primaryKey.extra != 'auto_increment') 36 | $column.columnName, 37 | #end 38 | #end 39 | 40 | 41 | #foreach($column in $columns) 42 | #if($column.columnName != $primaryKey.columnName || $primaryKey.extra != 'auto_increment') 43 | #{$column.attrname}, 44 | #end 45 | #end 46 | 47 | 48 | 49 | 50 | update ${tableName} 51 | 52 | #foreach($column in $columns) 53 | #if($column.columnName != $primaryKey.columnName) 54 | $column.columnName = #{$column.attrname}, 55 | #end 56 | #end 57 | 58 | where ${primaryKey.columnName} = #{${primaryKey.attrname}} 59 | 60 | 61 | 62 | delete from ${tableName} where ${primaryKey.columnName} = #{${primaryKey.attrname}} 63 | 64 | 65 | 66 | delete from ${tableName} where ${primaryKey.columnName} in 67 | 68 | #{${primaryKey.attrname}} 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /src/main/resources/vm/java/Controller.java.vm: -------------------------------------------------------------------------------- 1 | package ${basePackage}.web.controller.${moduleName}; 2 | 3 | import java.util.List; 4 | import org.apache.shiro.authz.annotation.RequiresPermissions; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.ui.ModelMap; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PathVariable; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.ResponseBody; 13 | import com.sue.common.annotation.Log; 14 | import com.sue.common.enums.BusinessType; 15 | import ${package}.domain.${className}; 16 | import ${package}.service.I${className}Service; 17 | import com.sue.common.core.controller.BaseController; 18 | import com.sue.common.core.page.TableDataInfo; 19 | import com.sue.common.core.domain.AjaxResult; 20 | import com.sue.common.utils.poi.ExcelUtil; 21 | 22 | /** 23 | * ${tableComment} 信息操作处理 24 | * 25 | * @author ${author} 26 | * @date ${datetime} 27 | */ 28 | @Controller 29 | @RequestMapping("/${moduleName}/${classname}") 30 | public class ${className}Controller extends BaseController 31 | { 32 | private String prefix = "${moduleName}/${classname}"; 33 | 34 | @Autowired 35 | private I${className}Service ${classname}Service; 36 | 37 | @RequiresPermissions("${moduleName}:${classname}:view") 38 | @GetMapping() 39 | public String ${classname}() 40 | { 41 | return prefix + "/${classname}"; 42 | } 43 | 44 | /** 45 | * 查询${tableComment}列表 46 | */ 47 | @RequiresPermissions("${moduleName}:${classname}:list") 48 | @PostMapping("/list") 49 | @ResponseBody 50 | public TableDataInfo list(${className} ${classname}) 51 | { 52 | startPage(); 53 | List<${className}> list = ${classname}Service.select${className}List(${classname}); 54 | return getDataTable(list); 55 | } 56 | 57 | 58 | /** 59 | * 导出${tableComment}列表 60 | */ 61 | @RequiresPermissions("${moduleName}:${classname}:export") 62 | @PostMapping("/export") 63 | @ResponseBody 64 | public AjaxResult export(${className} ${classname}) 65 | { 66 | List<${className}> list = ${classname}Service.select${className}List(${classname}); 67 | ExcelUtil<${className}> util = new ExcelUtil<${className}>(${className}.class); 68 | return util.exportExcel(list, "${classname}"); 69 | } 70 | 71 | /** 72 | * 新增${tableComment} 73 | */ 74 | @GetMapping("/add") 75 | public String add() 76 | { 77 | return prefix + "/add"; 78 | } 79 | 80 | /** 81 | * 新增保存${tableComment} 82 | */ 83 | @RequiresPermissions("${moduleName}:${classname}:add") 84 | @Log(title = "${tableComment}", businessType = BusinessType.INSERT) 85 | @PostMapping("/add") 86 | @ResponseBody 87 | public AjaxResult addSave(${className} ${classname}) 88 | { 89 | return toAjax(${classname}Service.insert${className}(${classname})); 90 | } 91 | 92 | /** 93 | * 修改${tableComment} 94 | */ 95 | @GetMapping("/edit/{${primaryKey.attrname}}") 96 | public String edit(@PathVariable("${primaryKey.attrname}") ${primaryKey.attrType} ${primaryKey.attrname}, ModelMap mmap) 97 | { 98 | ${className} ${classname} = ${classname}Service.select${className}ById(${primaryKey.attrname}); 99 | mmap.put("${classname}", ${classname}); 100 | return prefix + "/edit"; 101 | } 102 | 103 | /** 104 | * 修改保存${tableComment} 105 | */ 106 | @RequiresPermissions("${moduleName}:${classname}:edit") 107 | @Log(title = "${tableComment}", businessType = BusinessType.UPDATE) 108 | @PostMapping("/edit") 109 | @ResponseBody 110 | public AjaxResult editSave(${className} ${classname}) 111 | { 112 | return toAjax(${classname}Service.update${className}(${classname})); 113 | } 114 | 115 | /** 116 | * 删除${tableComment} 117 | */ 118 | @RequiresPermissions("${moduleName}:${classname}:remove") 119 | @Log(title = "${tableComment}", businessType = BusinessType.DELETE) 120 | @PostMapping( "/remove") 121 | @ResponseBody 122 | public AjaxResult remove(String ids) 123 | { 124 | return toAjax(${classname}Service.delete${className}ByIds(ids)); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /src/main/resources/templates/tool/gen/gen.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 |
10 |
11 |
12 |
    13 |
  • 14 | 表名称: 15 |
  • 16 |
  • 17 | 表描述: 18 |
  • 19 |
  • 20 | 21 | 22 | - 23 | 24 |
  • 25 |
  • 26 |  搜索 27 |  重置 28 |
  • 29 |
30 |
31 |
32 |
33 | 34 | 39 | 40 |
41 |
42 |
43 |
44 |
45 | 46 | 122 | 123 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/service/impl/GenServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.service.impl; 2 | 3 | 4 | import com.sue.generate.config.GenConfig; 5 | import com.sue.generate.domain.ColumnInfo; 6 | import com.sue.generate.domain.TableInfo; 7 | import com.sue.generate.mapper.GenMapper; 8 | import com.sue.generate.service.IGenService; 9 | import com.sue.generate.util.CharsetKit; 10 | import com.sue.generate.util.GenUtils; 11 | import com.sue.generate.util.VelocityInitializer; 12 | import lombok.extern.slf4j.Slf4j; 13 | import org.apache.commons.io.IOUtils; 14 | import org.apache.commons.lang3.StringUtils; 15 | import org.apache.velocity.Template; 16 | import org.apache.velocity.VelocityContext; 17 | import org.apache.velocity.app.Velocity; 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.stereotype.Service; 20 | 21 | import java.io.ByteArrayOutputStream; 22 | import java.io.StringWriter; 23 | import java.util.List; 24 | import java.util.zip.ZipEntry; 25 | import java.util.zip.ZipOutputStream; 26 | 27 | /** 28 | * 代码生成 服务层处理 29 | * 30 | * @author sue 31 | */ 32 | @Slf4j 33 | @Service 34 | public class GenServiceImpl implements IGenService { 35 | 36 | @Autowired 37 | private GenMapper genMapper; 38 | 39 | /** 40 | * 查询ry数据库表信息 41 | * 42 | * @param tableInfo 表信息 43 | * @return 数据库表列表 44 | */ 45 | @Override 46 | public List selectTableList(TableInfo tableInfo) { 47 | return genMapper.selectTableList(tableInfo); 48 | } 49 | 50 | /** 51 | * 生成代码 52 | * 53 | * @param author 作者 54 | * @param packageName 包名称 55 | * @param dataBaseName 库名称 56 | * @param tableName 表名称 57 | * @return 数据 58 | */ 59 | @Override 60 | public byte[] generatorCode(String author, String packageName, String dataBaseName, String tableName) { 61 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 62 | ZipOutputStream zip = new ZipOutputStream(outputStream); 63 | generatorCode(author, packageName, dataBaseName, tableName, zip); 64 | IOUtils.closeQuietly(zip); 65 | return outputStream.toByteArray(); 66 | } 67 | 68 | /** 69 | * 批量生成代码 70 | * 71 | * @param author 作者 72 | * @param packageName 包名称 73 | * @param dataBaseName 库名称 74 | * @param tableNames 表数组 75 | * @return 数据 76 | */ 77 | @Override 78 | public byte[] generatorCode(String author, String packageName, String dataBaseName, String[] tableNames) { 79 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 80 | ZipOutputStream zip = new ZipOutputStream(outputStream); 81 | for (String tableName : tableNames) { 82 | generatorCode(author, packageName, dataBaseName, tableName, zip); 83 | } 84 | IOUtils.closeQuietly(zip); 85 | return outputStream.toByteArray(); 86 | } 87 | 88 | /** 89 | * 查询表信息并生成代码 90 | */ 91 | private void generatorCode(String author, String packageName, String dataBaseName, String tableName, ZipOutputStream zip) { 92 | // 查询表信息 93 | TableInfo table = genMapper.selectTableByName(dataBaseName, tableName); 94 | // 查询列信息 95 | List columns = genMapper.selectTableColumnsByName(dataBaseName, tableName); 96 | 97 | // 表名转换成Java属性名 98 | String className = GenUtils.tableToJava(table.getTableName()); 99 | table.setClassName(className); 100 | table.setClassname(StringUtils.uncapitalize(className)); 101 | // 列信息 102 | table.setColumns(GenUtils.transColums(columns)); 103 | // 设置主键 104 | table.setPrimaryKey(table.getColumnsLast()); 105 | 106 | VelocityInitializer.initVelocity(); 107 | 108 | String realPackageName; 109 | if (StringUtils.isEmpty(packageName)) { 110 | realPackageName = GenConfig.getPackageName(); 111 | } else { 112 | realPackageName = packageName; 113 | } 114 | String moduleName = GenUtils.getModuleName(realPackageName); 115 | 116 | VelocityContext context = GenUtils.getVelocityContext(author, realPackageName, table); 117 | 118 | // 获取模板列表 119 | List templates = GenUtils.getTemplates(); 120 | log.info("templates:{}", templates.toString()); 121 | for (String template : templates) { 122 | // 渲染模板 123 | StringWriter sw = new StringWriter(); 124 | Template tpl = Velocity.getTemplate(template, CharsetKit.UTF_8); 125 | tpl.merge(context, sw); 126 | try { 127 | log.info("realPackageName:{},template:{},moduleName:{}", realPackageName, template, moduleName); 128 | // 添加到zip 129 | String fileName = GenUtils.getFileName(realPackageName, template, table, moduleName); 130 | log.info("fileName:{}", fileName); 131 | zip.putNextEntry(new ZipEntry(fileName)); 132 | IOUtils.write(sw.toString(), zip, CharsetKit.UTF_8); 133 | IOUtils.closeQuietly(sw); 134 | zip.closeEntry(); 135 | } catch (Exception e) { 136 | log.error("渲染模板失败,表名: {}", table.getTableName(), e); 137 | } 138 | } 139 | log.info("渲染模成功,表名:{}", table.getTableName()); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/main/resources/vm/html/list.html.vm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 |
10 |
11 |
12 |
    13 | #foreach($column in $columns) 14 | #if($column.columnName != $primaryKey.columnName) 15 | #if(!${column.configInfo}) 16 |
  • 17 | ${column.columnComment}: 18 |
  • 19 | 20 | #else 21 | #if(${column.configInfo.type} == "dict") 22 |
  • 23 | ${column.columnComment}: 27 |
  • 28 | #elseif(${column.configInfo.type} == "date") 29 |
  • 30 | 31 | 32 | - 33 | 34 |
  • 35 | #elseif(${column.configInfo.type} == "fk") 36 | #end 37 | #end 38 | #end 39 | #end 40 |
  • 41 |  搜索 42 |  重置 43 |
  • 44 |
45 |
46 |
47 |
48 | 49 | 63 |
64 |
65 |
66 |
67 |
68 |
69 | 131 | 132 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/util/GenUtils.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.util; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.format.DateTimeFormatter; 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | import org.apache.velocity.VelocityContext; 11 | import com.sue.generate.config.GenConfig; 12 | import com.sue.generate.domain.ColumnInfo; 13 | import com.sue.generate.domain.TableInfo; 14 | 15 | /** 16 | * 代码生成器 工具类 17 | * 18 | * @author sue 19 | */ 20 | public class GenUtils { 21 | 22 | /** 23 | * mybatis空间路径 24 | */ 25 | private static final String MYBATIS_PATH = "main/resources/mapper"; 26 | 27 | /** 28 | * html空间路径 29 | */ 30 | private static final String TEMPLATES_PATH = "main/resources/templates"; 31 | 32 | /** 33 | * 类型转换 34 | */ 35 | public static Map javaTypeMap = new HashMap(); 36 | 37 | /** 38 | * 设置列信息 39 | */ 40 | public static List transColums(List columns) { 41 | // 列信息 42 | List columsList = new ArrayList<>(); 43 | for (ColumnInfo column : columns) { 44 | // 列名转换成Java属性名 45 | String attrName = StringUtils.convertToCamelCase(column.getColumnName()); 46 | column.setAttrName(attrName); 47 | column.setAttrname(StringUtils.uncapitalize(attrName)); 48 | column.setExtra(column.getExtra()); 49 | 50 | // 列的数据类型,转换成Java类型 51 | String attrType = javaTypeMap.get(column.getDataType()); 52 | column.setAttrType(attrType); 53 | 54 | columsList.add(column); 55 | } 56 | return columsList; 57 | } 58 | 59 | /** 60 | * 获取模板信息 61 | * 62 | * @return 模板列表 63 | */ 64 | public static VelocityContext getVelocityContext(String author, String packageName, TableInfo table) { 65 | // java对象数据传递到模板文件vm 66 | VelocityContext velocityContext = new VelocityContext(); 67 | velocityContext.put("tableName", table.getTableName()); 68 | velocityContext.put("tableComment", replaceKeyword(table.getTableComment())); 69 | velocityContext.put("primaryKey", table.getPrimaryKey()); 70 | velocityContext.put("className", table.getClassName()); 71 | velocityContext.put("classname", table.getClassname()); 72 | velocityContext.put("moduleName", getModuleName(packageName)); 73 | velocityContext.put("columns", table.getColumns()); 74 | velocityContext.put("basePackage", packageName); 75 | velocityContext.put("package", packageName); 76 | velocityContext.put("author", author); 77 | velocityContext.put("datetime", now()); 78 | return velocityContext; 79 | } 80 | 81 | private static String now() { 82 | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 83 | LocalDateTime localDateTime = LocalDateTime.now(); 84 | return localDateTime.format(formatter); 85 | } 86 | 87 | /** 88 | * 获取模板信息 89 | * 90 | * @return 模板列表 91 | */ 92 | public static List getTemplates() { 93 | List templates = new ArrayList(); 94 | templates.add("vm/java/domain.java.vm"); 95 | templates.add("vm/java/Mapper.java.vm"); 96 | templates.add("vm/java/Service.java.vm"); 97 | templates.add("vm/java/ServiceImpl.java.vm"); 98 | templates.add("vm/java/Controller.java.vm"); 99 | templates.add("vm/xml/Mapper.xml.vm"); 100 | templates.add("vm/html/list.html.vm"); 101 | templates.add("vm/html/add.html.vm"); 102 | templates.add("vm/html/edit.html.vm"); 103 | templates.add("vm/sql/sql.vm"); 104 | return templates; 105 | } 106 | 107 | /** 108 | * 表名转换成Java类名 109 | */ 110 | public static String tableToJava(String tableName) { 111 | String autoRemovePre = GenConfig.getAutoRemovePre(); 112 | String tablePrefix = GenConfig.getTablePrefix(); 113 | if ("true".equals(autoRemovePre) && StringUtils.isNotEmpty(tablePrefix)) { 114 | tableName = tableName.replaceFirst(tablePrefix, ""); 115 | } 116 | return StringUtils.convertToCamelCase(tableName); 117 | } 118 | 119 | /** 120 | * 获取文件名 121 | */ 122 | public static String getFileName(String packageName, String template, TableInfo table, String moduleName) { 123 | // 小写类名 124 | String classname = table.getClassname(); 125 | // 大写类名 126 | String className = table.getClassName(); 127 | String javaPath = getProjectPath(packageName); 128 | String mybatisPath = MYBATIS_PATH + "/" + moduleName + "/" + className; 129 | String htmlPath = TEMPLATES_PATH + "/" + moduleName + "/" + classname; 130 | 131 | if (template.contains("domain.java.vm")) { 132 | return javaPath + "domain" + "/" + className + ".java"; 133 | } 134 | 135 | if (template.contains("Mapper.java.vm")) { 136 | return javaPath + "mapper" + "/" + className + "Mapper.java"; 137 | } 138 | 139 | if (template.contains("Service.java.vm")) { 140 | return javaPath + "service" + "/" + "I" + className + "Service.java"; 141 | } 142 | 143 | if (template.contains("ServiceImpl.java.vm")) { 144 | return javaPath + "service" + "/impl/" + className + "ServiceImpl.java"; 145 | } 146 | 147 | if (template.contains("Controller.java.vm")) { 148 | return javaPath + "controller" + "/" + className + "Controller.java"; 149 | } 150 | 151 | if (template.contains("Mapper.xml.vm")) { 152 | return mybatisPath + "Mapper.xml"; 153 | } 154 | 155 | if (template.contains("list.html.vm")) { 156 | return htmlPath + "/" + classname + ".html"; 157 | } 158 | if (template.contains("add.html.vm")) { 159 | return htmlPath + "/" + "add.html"; 160 | } 161 | if (template.contains("edit.html.vm")) { 162 | return htmlPath + "/" + "edit.html"; 163 | } 164 | if (template.contains("sql.vm")) { 165 | return classname + "Menu.sql"; 166 | } 167 | return null; 168 | } 169 | 170 | /** 171 | * 获取模块名 172 | * 173 | * @param packageName 包名 174 | * @return 模块名 175 | */ 176 | public static String getModuleName(String packageName) { 177 | int lastIndex = packageName.lastIndexOf("."); 178 | int nameLength = packageName.length(); 179 | String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength); 180 | return moduleName; 181 | } 182 | 183 | public static String getBasePackage(String packageName) { 184 | int lastIndex = packageName.lastIndexOf("."); 185 | String basePackage = StringUtils.substring(packageName, 0, lastIndex); 186 | return basePackage; 187 | } 188 | 189 | public static String getProjectPath(String packageName) { 190 | StringBuffer projectPath = new StringBuffer(); 191 | projectPath.append("main/java/"); 192 | projectPath.append(packageName.replace(".", "/")); 193 | projectPath.append("/"); 194 | return projectPath.toString(); 195 | } 196 | 197 | public static String replaceKeyword(String keyword) { 198 | String keyName = keyword.replaceAll("(?:表|信息|管理)", ""); 199 | return keyName; 200 | } 201 | 202 | static { 203 | javaTypeMap.put("tinyint", "Integer"); 204 | javaTypeMap.put("smallint", "Integer"); 205 | javaTypeMap.put("mediumint", "Integer"); 206 | javaTypeMap.put("int", "Integer"); 207 | javaTypeMap.put("number", "Integer"); 208 | javaTypeMap.put("integer", "integer"); 209 | javaTypeMap.put("bigint", "Long"); 210 | javaTypeMap.put("float", "Float"); 211 | javaTypeMap.put("double", "Double"); 212 | javaTypeMap.put("decimal", "BigDecimal"); 213 | javaTypeMap.put("bit", "Boolean"); 214 | javaTypeMap.put("char", "String"); 215 | javaTypeMap.put("varchar", "String"); 216 | javaTypeMap.put("varchar2", "String"); 217 | javaTypeMap.put("tinytext", "String"); 218 | javaTypeMap.put("text", "String"); 219 | javaTypeMap.put("mediumtext", "String"); 220 | javaTypeMap.put("longtext", "String"); 221 | javaTypeMap.put("time", "Date"); 222 | javaTypeMap.put("date", "Date"); 223 | javaTypeMap.put("datetime", "Date"); 224 | javaTypeMap.put("timestamp", "Date"); 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/util/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.util; 2 | 3 | 4 | import java.util.Collection; 5 | import java.util.Map; 6 | 7 | /** 8 | * 字符串工具类 9 | * 10 | * @author sue 11 | */ 12 | public class StringUtils extends org.apache.commons.lang3.StringUtils { 13 | /** 14 | * 空字符串 15 | */ 16 | private static final String NULLSTR = ""; 17 | 18 | /** 19 | * 下划线 20 | */ 21 | private static final char SEPARATOR = '_'; 22 | 23 | /** 24 | * 获取参数不为空值 25 | * 26 | * @param value defaultValue 要判断的value 27 | * @return value 返回值 28 | */ 29 | public static T nvl(T value, T defaultValue) { 30 | return value != null ? value : defaultValue; 31 | } 32 | 33 | /** 34 | * * 判断一个Collection是否为空, 包含List,Set,Queue 35 | * 36 | * @param coll 要判断的Collection 37 | * @return true:为空 false:非空 38 | */ 39 | public static boolean isEmpty(Collection coll) { 40 | return isNull(coll) || coll.isEmpty(); 41 | } 42 | 43 | /** 44 | * * 判断一个Collection是否非空,包含List,Set,Queue 45 | * 46 | * @param coll 要判断的Collection 47 | * @return true:非空 false:空 48 | */ 49 | public static boolean isNotEmpty(Collection coll) { 50 | return !isEmpty(coll); 51 | } 52 | 53 | /** 54 | * * 判断一个对象数组是否为空 55 | * 56 | * @param objects 要判断的对象数组 57 | * * @return true:为空 false:非空 58 | */ 59 | public static boolean isEmpty(Object[] objects) { 60 | return isNull(objects) || (objects.length == 0); 61 | } 62 | 63 | /** 64 | * * 判断一个对象数组是否非空 65 | * 66 | * @param objects 要判断的对象数组 67 | * @return true:非空 false:空 68 | */ 69 | public static boolean isNotEmpty(Object[] objects) { 70 | return !isEmpty(objects); 71 | } 72 | 73 | /** 74 | * * 判断一个Map是否为空 75 | * 76 | * @param map 要判断的Map 77 | * @return true:为空 false:非空 78 | */ 79 | public static boolean isEmpty(Map map) { 80 | return isNull(map) || map.isEmpty(); 81 | } 82 | 83 | /** 84 | * * 判断一个Map是否为空 85 | * 86 | * @param map 要判断的Map 87 | * @return true:非空 false:空 88 | */ 89 | public static boolean isNotEmpty(Map map) { 90 | return !isEmpty(map); 91 | } 92 | 93 | /** 94 | * * 判断一个字符串是否为空串 95 | * 96 | * @param str String 97 | * @return true:为空 false:非空 98 | */ 99 | public static boolean isEmpty(String str) { 100 | return isNull(str) || NULLSTR.equals(str.trim()); 101 | } 102 | 103 | /** 104 | * * 判断一个字符串是否为非空串 105 | * 106 | * @param str String 107 | * @return true:非空串 false:空串 108 | */ 109 | public static boolean isNotEmpty(String str) { 110 | return !isEmpty(str); 111 | } 112 | 113 | /** 114 | * * 判断一个对象是否为空 115 | * 116 | * @param object Object 117 | * @return true:为空 false:非空 118 | */ 119 | public static boolean isNull(Object object) { 120 | return object == null; 121 | } 122 | 123 | /** 124 | * * 判断一个对象是否非空 125 | * 126 | * @param object Object 127 | * @return true:非空 false:空 128 | */ 129 | public static boolean isNotNull(Object object) { 130 | return !isNull(object); 131 | } 132 | 133 | /** 134 | * * 判断一个对象是否是数组类型(Java基本型别的数组) 135 | * 136 | * @param object 对象 137 | * @return true:是数组 false:不是数组 138 | */ 139 | public static boolean isArray(Object object) { 140 | return isNotNull(object) && object.getClass().isArray(); 141 | } 142 | 143 | /** 144 | * 去空格 145 | */ 146 | public static String trim(String str) { 147 | return (str == null ? "" : str.trim()); 148 | } 149 | 150 | /** 151 | * 截取字符串 152 | * 153 | * @param str 字符串 154 | * @param start 开始 155 | * @return 结果 156 | */ 157 | public static String substring(final String str, int start) { 158 | if (str == null) { 159 | return NULLSTR; 160 | } 161 | 162 | if (start < 0) { 163 | start = str.length() + start; 164 | } 165 | 166 | if (start < 0) { 167 | start = 0; 168 | } 169 | if (start > str.length()) { 170 | return NULLSTR; 171 | } 172 | 173 | return str.substring(start); 174 | } 175 | 176 | /** 177 | * 截取字符串 178 | * 179 | * @param str 字符串 180 | * @param start 开始 181 | * @param end 结束 182 | * @return 结果 183 | */ 184 | public static String substring(final String str, int start, int end) { 185 | if (str == null) { 186 | return NULLSTR; 187 | } 188 | 189 | if (end < 0) { 190 | end = str.length() + end; 191 | } 192 | if (start < 0) { 193 | start = str.length() + start; 194 | } 195 | 196 | if (end > str.length()) { 197 | end = str.length(); 198 | } 199 | 200 | if (start > end) { 201 | return NULLSTR; 202 | } 203 | 204 | if (start < 0) { 205 | start = 0; 206 | } 207 | if (end < 0) { 208 | end = 0; 209 | } 210 | 211 | return str.substring(start, end); 212 | } 213 | 214 | /** 215 | * 格式化文本, {} 表示占位符
216 | * 此方法只是简单将占位符 {} 按照顺序替换为参数
217 | * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
218 | * 例:
219 | * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
220 | * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
221 | * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
222 | * 223 | * @param template 文本模板,被替换的部分用 {} 表示 224 | * @param params 参数值 225 | * @return 格式化后的文本 226 | */ 227 | public static String format(String template, Object... params) { 228 | if (isEmpty(params) || isEmpty(template)) { 229 | return template; 230 | } 231 | return StrFormatter.format(template, params); 232 | } 233 | 234 | /** 235 | * 下划线转驼峰命名 236 | */ 237 | public static String toUnderScoreCase(String str) { 238 | if (str == null) { 239 | return null; 240 | } 241 | StringBuilder sb = new StringBuilder(); 242 | // 前置字符是否大写 243 | boolean preCharIsUpperCase = true; 244 | // 当前字符是否大写 245 | boolean curreCharIsUpperCase = true; 246 | // 下一字符是否大写 247 | boolean nexteCharIsUpperCase = true; 248 | for (int i = 0; i < str.length(); i++) { 249 | char c = str.charAt(i); 250 | if (i > 0) { 251 | preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1)); 252 | } else { 253 | preCharIsUpperCase = false; 254 | } 255 | 256 | curreCharIsUpperCase = Character.isUpperCase(c); 257 | 258 | if (i < (str.length() - 1)) { 259 | nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1)); 260 | } 261 | 262 | if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) { 263 | sb.append(SEPARATOR); 264 | } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) { 265 | sb.append(SEPARATOR); 266 | } 267 | sb.append(Character.toLowerCase(c)); 268 | } 269 | 270 | return sb.toString(); 271 | } 272 | 273 | /** 274 | * 是否包含字符串 275 | * 276 | * @param str 验证字符串 277 | * @param strs 字符串组 278 | * @return 包含返回true 279 | */ 280 | public static boolean inStringIgnoreCase(String str, String... strs) { 281 | if (str != null && strs != null) { 282 | for (String s : strs) { 283 | if (str.equalsIgnoreCase(trim(s))) { 284 | return true; 285 | } 286 | } 287 | } 288 | return false; 289 | } 290 | 291 | /** 292 | * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld 293 | * 294 | * @param name 转换前的下划线大写方式命名的字符串 295 | * @return 转换后的驼峰式命名的字符串 296 | */ 297 | public static String convertToCamelCase(String name) { 298 | StringBuilder result = new StringBuilder(); 299 | // 快速检查 300 | if (name == null || name.isEmpty()) { 301 | // 没必要转换 302 | return ""; 303 | } else if (!name.contains("_")) { 304 | // 不含下划线,仅将首字母大写 305 | return name.substring(0, 1).toUpperCase() + name.substring(1); 306 | } 307 | // 用下划线将原始字符串分割 308 | String[] camels = name.split("_"); 309 | for (String camel : camels) { 310 | // 跳过原始字符串中开头、结尾的下换线或双重下划线 311 | if (camel.isEmpty()) { 312 | continue; 313 | } 314 | // 首字母大写 315 | result.append(camel.substring(0, 1).toUpperCase()); 316 | result.append(camel.substring(1).toLowerCase()); 317 | } 318 | return result.toString(); 319 | } 320 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.sue.tool 8 | code-generate 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | 1.0-SNAPSHOT 14 | UTF-8 15 | 1.8 16 | 1.1.14 17 | 2.0.8.RELEASE 18 | 2.0.8.RELEASE 19 | 1.2.2 20 | 1.7.25 21 | 1.18.4 22 | 2.6 23 | 3.8.1 24 | 4.2 25 | 1.2.54 26 | 2.9.7 27 | 4.12 28 | 1.19 29 | 1.3.1 30 | 1.1.10 31 | 32 | 33 | 34 | 35 | ${project.artifactId} 36 | 37 | 38 | 39 | 40 | 41 | org.apache.maven.plugins 42 | maven-compiler-plugin 43 | 3.8.0 44 | 45 | 1.8 46 | 1.8 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-maven-plugin 52 | 1.5.18.RELEASE 53 | 54 | true 55 | exec 56 | 57 | service 58 | 59 | 60 | 61 | 62 | 63 | repackage 64 | build-info 65 | 66 | 67 | 68 | 69 | 70 | org.apache.maven.plugins 71 | maven-checkstyle-plugin 72 | 3.0.0 73 | 74 | checkstyle.xml 75 | UTF-8 76 | true 77 | false 78 | false 79 | 0 80 | warning 81 | 82 | 83 | 84 | checkstyle 85 | validate 86 | 87 | check 88 | 89 | 90 | 91 | 92 | 93 | com.puppycrawl.tools 94 | checkstyle 95 | 8.15 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | org.apache.maven.plugins 106 | maven-checkstyle-plugin 107 | 108 | 109 | org.springframework.boot 110 | spring-boot-maven-plugin 111 | 112 | true 113 | 114 | 115 | 116 | org.apache.maven.plugins 117 | maven-compiler-plugin 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | org.springframework.boot 126 | spring-boot-dependencies 127 | ${spring.boot.version} 128 | pom 129 | import 130 | 131 | 132 | org.slf4j 133 | slf4j-api 134 | ${slf4j.version} 135 | 136 | 137 | ch.qos.logback 138 | logback-core 139 | ${logback.version} 140 | 141 | 142 | ch.qos.logback 143 | logback-classic 144 | ${logback.version} 145 | 146 | 147 | org.mybatis.spring.boot 148 | mybatis-spring-boot-starter 149 | ${mybatis-spring-boot-starter.version} 150 | 151 | 152 | com.alibaba 153 | druid-spring-boot-starter 154 | ${druid-spring-boot-starter.version} 155 | 156 | 157 | org.projectlombok 158 | lombok 159 | ${lombok.version} 160 | 161 | 162 | 163 | commons-io 164 | commons-io 165 | ${commons-io.version} 166 | 167 | 168 | org.apache.commons 169 | commons-lang3 170 | ${commons-lang3.version} 171 | 172 | 173 | org.apache.commons 174 | commons-collections4 175 | ${commons-collections4.version} 176 | 177 | 178 | com.alibaba 179 | fastjson 180 | ${fastjson.version} 181 | 182 | 183 | com.fasterxml.jackson.core 184 | jackson-databind 185 | ${jackson.version} 186 | 187 | 188 | junit 189 | junit 190 | ${junit.version} 191 | test 192 | 193 | 194 | 195 | 196 | eu.bitwalker 197 | UserAgentUtils 198 | ${bitwalker.version} 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | org.springframework 208 | spring-context 209 | 210 | 211 | org.springframework.boot 212 | spring-boot-starter-web 213 | 214 | 215 | org.springframework.boot 216 | spring-boot-starter-test 217 | test 218 | 219 | 220 | 221 | org.mybatis.spring.boot 222 | mybatis-spring-boot-starter 223 | 224 | 225 | 226 | com.alibaba 227 | druid-spring-boot-starter 228 | 229 | 230 | 231 | com.alibaba 232 | fastjson 233 | 234 | 235 | com.fasterxml.jackson.core 236 | jackson-databind 237 | 238 | 239 | 240 | mysql 241 | mysql-connector-java 242 | 243 | 244 | org.springframework.boot 245 | spring-boot-starter-actuator 246 | 247 | 248 | com.fasterxml.jackson.core 249 | jackson-annotations 250 | 2.9.4 251 | compile 252 | 253 | 254 | org.apache.commons 255 | commons-lang3 256 | 257 | 258 | 259 | org.apache.httpcomponents 260 | httpmime 261 | 262 | 263 | 264 | org.projectlombok 265 | lombok 266 | 267 | 268 | 269 | org.apache.commons 270 | commons-lang3 271 | 3.8.1 272 | 273 | 274 | 275 | commons-io 276 | commons-io 277 | 2.5 278 | 279 | 280 | 281 | io.springfox 282 | springfox-swagger2 283 | 2.9.2 284 | 285 | 286 | io.springfox 287 | springfox-swagger-ui 288 | 2.9.2 289 | 290 | 291 | 292 | 293 | org.apache.velocity 294 | velocity 295 | 1.7 296 | 297 | 298 | com.fasterxml.jackson.core 299 | jackson-annotations 300 | 2.9.4 301 | compile 302 | 303 | 304 | -------------------------------------------------------------------------------- /src/main/java/com/sue/generate/util/Convert.java: -------------------------------------------------------------------------------- 1 | package com.sue.generate.util; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.BigInteger; 5 | import java.nio.ByteBuffer; 6 | import java.nio.charset.Charset; 7 | import java.text.NumberFormat; 8 | import java.util.Set; 9 | 10 | /** 11 | * 类型转换器 12 | * 13 | * @author sue 14 | */ 15 | public class Convert { 16 | /** 17 | * 转换为字符串
18 | * 如果给定的值为null,或者转换失败,返回默认值
19 | * 转换失败不会报错 20 | * 21 | * @param value 被转换的值 22 | * @param defaultValue 转换错误时的默认值 23 | * @return 结果 24 | */ 25 | public static String toStr(Object value, String defaultValue) { 26 | if (null == value) { 27 | return defaultValue; 28 | } 29 | if (value instanceof String) { 30 | return (String) value; 31 | } 32 | return value.toString(); 33 | } 34 | 35 | /** 36 | * 转换为字符串
37 | * 如果给定的值为null,或者转换失败,返回默认值null
38 | * 转换失败不会报错 39 | * 40 | * @param value 被转换的值 41 | * @return 结果 42 | */ 43 | public static String toStr(Object value) { 44 | return toStr(value, null); 45 | } 46 | 47 | /** 48 | * 转换为字符
49 | * 如果给定的值为null,或者转换失败,返回默认值
50 | * 转换失败不会报错 51 | * 52 | * @param value 被转换的值 53 | * @param defaultValue 转换错误时的默认值 54 | * @return 结果 55 | */ 56 | public static Character toChar(Object value, Character defaultValue) { 57 | if (null == value) { 58 | return defaultValue; 59 | } 60 | if (value instanceof Character) { 61 | return (Character) value; 62 | } 63 | 64 | final String valueStr = toStr(value, null); 65 | return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0); 66 | } 67 | 68 | /** 69 | * 转换为字符
70 | * 如果给定的值为null,或者转换失败,返回默认值null
71 | * 转换失败不会报错 72 | * 73 | * @param value 被转换的值 74 | * @return 结果 75 | */ 76 | public static Character toChar(Object value) { 77 | return toChar(value, null); 78 | } 79 | 80 | /** 81 | * 转换为byte
82 | * 如果给定的值为null,或者转换失败,返回默认值
83 | * 转换失败不会报错 84 | * 85 | * @param value 被转换的值 86 | * @param defaultValue 转换错误时的默认值 87 | * @return 结果 88 | */ 89 | public static Byte toByte(Object value, Byte defaultValue) { 90 | if (value == null) { 91 | return defaultValue; 92 | } 93 | if (value instanceof Byte) { 94 | return (Byte) value; 95 | } 96 | if (value instanceof Number) { 97 | return ((Number) value).byteValue(); 98 | } 99 | final String valueStr = toStr(value, null); 100 | if (StringUtils.isEmpty(valueStr)) { 101 | return defaultValue; 102 | } 103 | try { 104 | return Byte.parseByte(valueStr); 105 | } catch (Exception e) { 106 | return defaultValue; 107 | } 108 | } 109 | 110 | /** 111 | * 转换为byte
112 | * 如果给定的值为null,或者转换失败,返回默认值null
113 | * 转换失败不会报错 114 | * 115 | * @param value 被转换的值 116 | * @return 结果 117 | */ 118 | public static Byte toByte(Object value) { 119 | return toByte(value, null); 120 | } 121 | 122 | /** 123 | * 转换为Short
124 | * 如果给定的值为null,或者转换失败,返回默认值
125 | * 转换失败不会报错 126 | * 127 | * @param value 被转换的值 128 | * @param defaultValue 转换错误时的默认值 129 | * @return 结果 130 | */ 131 | public static Short toShort(Object value, Short defaultValue) { 132 | if (value == null) { 133 | return defaultValue; 134 | } 135 | if (value instanceof Short) { 136 | return (Short) value; 137 | } 138 | if (value instanceof Number) { 139 | return ((Number) value).shortValue(); 140 | } 141 | final String valueStr = toStr(value, null); 142 | if (StringUtils.isEmpty(valueStr)) { 143 | return defaultValue; 144 | } 145 | try { 146 | return Short.parseShort(valueStr.trim()); 147 | } catch (Exception e) { 148 | return defaultValue; 149 | } 150 | } 151 | 152 | /** 153 | * 转换为Short
154 | * 如果给定的值为null,或者转换失败,返回默认值null
155 | * 转换失败不会报错 156 | * 157 | * @param value 被转换的值 158 | * @return 结果 159 | */ 160 | public static Short toShort(Object value) { 161 | return toShort(value, null); 162 | } 163 | 164 | /** 165 | * 转换为Number
166 | * 如果给定的值为空,或者转换失败,返回默认值
167 | * 转换失败不会报错 168 | * 169 | * @param value 被转换的值 170 | * @param defaultValue 转换错误时的默认值 171 | * @return 结果 172 | */ 173 | public static Number toNumber(Object value, Number defaultValue) { 174 | if (value == null) { 175 | return defaultValue; 176 | } 177 | if (value instanceof Number) { 178 | return (Number) value; 179 | } 180 | final String valueStr = toStr(value, null); 181 | if (StringUtils.isEmpty(valueStr)) { 182 | return defaultValue; 183 | } 184 | try { 185 | return NumberFormat.getInstance().parse(valueStr); 186 | } catch (Exception e) { 187 | return defaultValue; 188 | } 189 | } 190 | 191 | /** 192 | * 转换为Number
193 | * 如果给定的值为空,或者转换失败,返回默认值null
194 | * 转换失败不会报错 195 | * 196 | * @param value 被转换的值 197 | * @return 结果 198 | */ 199 | public static Number toNumber(Object value) { 200 | return toNumber(value, null); 201 | } 202 | 203 | /** 204 | * 转换为int
205 | * 如果给定的值为空,或者转换失败,返回默认值
206 | * 转换失败不会报错 207 | * 208 | * @param value 被转换的值 209 | * @param defaultValue 转换错误时的默认值 210 | * @return 结果 211 | */ 212 | public static Integer toInt(Object value, Integer defaultValue) { 213 | if (value == null) { 214 | return defaultValue; 215 | } 216 | if (value instanceof Integer) { 217 | return (Integer) value; 218 | } 219 | if (value instanceof Number) { 220 | return ((Number) value).intValue(); 221 | } 222 | final String valueStr = toStr(value, null); 223 | if (StringUtils.isEmpty(valueStr)) { 224 | return defaultValue; 225 | } 226 | try { 227 | return Integer.parseInt(valueStr.trim()); 228 | } catch (Exception e) { 229 | return defaultValue; 230 | } 231 | } 232 | 233 | /** 234 | * 转换为int
235 | * 如果给定的值为null,或者转换失败,返回默认值null
236 | * 转换失败不会报错 237 | * 238 | * @param value 被转换的值 239 | * @return 结果 240 | */ 241 | public static Integer toInt(Object value) { 242 | return toInt(value, null); 243 | } 244 | 245 | /** 246 | * 转换为Integer数组
247 | * 248 | * @param str 被转换的值 249 | * @return 结果 250 | */ 251 | public static Integer[] toIntArray(String str) { 252 | return toIntArray(",", str); 253 | } 254 | 255 | /** 256 | * 转换为Long数组
257 | * 258 | * @param str 被转换的值 259 | * @return 结果 260 | */ 261 | public static Long[] toLongArray(String str) { 262 | return toLongArray(",", str); 263 | } 264 | 265 | /** 266 | * 转换为Integer数组
267 | * 268 | * @param split 分隔符 269 | * @param split 被转换的值 270 | * @return 结果 271 | */ 272 | public static Integer[] toIntArray(String split, String str) { 273 | if (StringUtils.isEmpty(str)) { 274 | return new Integer[]{}; 275 | } 276 | String[] arr = str.split(split); 277 | final Integer[] ints = new Integer[arr.length]; 278 | for (int i = 0; i < arr.length; i++) { 279 | final Integer v = toInt(arr[i], 0); 280 | ints[i] = v; 281 | } 282 | return ints; 283 | } 284 | 285 | /** 286 | * 转换为Long数组
287 | * 288 | * @param split 分隔符 289 | * @param str 被转换的值 290 | * @return 结果 291 | */ 292 | public static Long[] toLongArray(String split, String str) { 293 | if (StringUtils.isEmpty(str)) { 294 | return new Long[]{}; 295 | } 296 | String[] arr = str.split(split); 297 | final Long[] longs = new Long[arr.length]; 298 | for (int i = 0; i < arr.length; i++) { 299 | final Long v = toLong(arr[i], null); 300 | longs[i] = v; 301 | } 302 | return longs; 303 | } 304 | 305 | /** 306 | * 转换为String数组
307 | * 308 | * @param str 被转换的值 309 | * @return 结果 310 | */ 311 | public static String[] toStrArray(String str) { 312 | return toStrArray(",", str); 313 | } 314 | 315 | /** 316 | * 转换为String数组
317 | * 318 | * @param split 分隔符 319 | * @param split 被转换的值 320 | * @return 结果 321 | */ 322 | public static String[] toStrArray(String split, String str) { 323 | return str.split(split); 324 | } 325 | 326 | /** 327 | * 转换为long
328 | * 如果给定的值为空,或者转换失败,返回默认值
329 | * 转换失败不会报错 330 | * 331 | * @param value 被转换的值 332 | * @param defaultValue 转换错误时的默认值 333 | * @return 结果 334 | */ 335 | public static Long toLong(Object value, Long defaultValue) { 336 | if (value == null) { 337 | return defaultValue; 338 | } 339 | if (value instanceof Long) { 340 | return (Long) value; 341 | } 342 | if (value instanceof Number) { 343 | return ((Number) value).longValue(); 344 | } 345 | final String valueStr = toStr(value, null); 346 | if (StringUtils.isEmpty(valueStr)) { 347 | return defaultValue; 348 | } 349 | try { 350 | // 支持科学计数法 351 | return new BigDecimal(valueStr.trim()).longValue(); 352 | } catch (Exception e) { 353 | return defaultValue; 354 | } 355 | } 356 | 357 | /** 358 | * 转换为long
359 | * 如果给定的值为null,或者转换失败,返回默认值null
360 | * 转换失败不会报错 361 | * 362 | * @param value 被转换的值 363 | * @return 结果 364 | */ 365 | public static Long toLong(Object value) { 366 | return toLong(value, null); 367 | } 368 | 369 | /** 370 | * 转换为double
371 | * 如果给定的值为空,或者转换失败,返回默认值
372 | * 转换失败不会报错 373 | * 374 | * @param value 被转换的值 375 | * @param defaultValue 转换错误时的默认值 376 | * @return 结果 377 | */ 378 | public static Double toDouble(Object value, Double defaultValue) { 379 | if (value == null) { 380 | return defaultValue; 381 | } 382 | if (value instanceof Double) { 383 | return (Double) value; 384 | } 385 | if (value instanceof Number) { 386 | return ((Number) value).doubleValue(); 387 | } 388 | final String valueStr = toStr(value, null); 389 | if (StringUtils.isEmpty(valueStr)) { 390 | return defaultValue; 391 | } 392 | try { 393 | // 支持科学计数法 394 | return new BigDecimal(valueStr.trim()).doubleValue(); 395 | } catch (Exception e) { 396 | return defaultValue; 397 | } 398 | } 399 | 400 | /** 401 | * 转换为double
402 | * 如果给定的值为空,或者转换失败,返回默认值null
403 | * 转换失败不会报错 404 | * 405 | * @param value 被转换的值 406 | * @return 结果 407 | */ 408 | public static Double toDouble(Object value) { 409 | return toDouble(value, null); 410 | } 411 | 412 | /** 413 | * 转换为Float
414 | * 如果给定的值为空,或者转换失败,返回默认值
415 | * 转换失败不会报错 416 | * 417 | * @param value 被转换的值 418 | * @param defaultValue 转换错误时的默认值 419 | * @return 结果 420 | */ 421 | public static Float toFloat(Object value, Float defaultValue) { 422 | if (value == null) { 423 | return defaultValue; 424 | } 425 | if (value instanceof Float) { 426 | return (Float) value; 427 | } 428 | if (value instanceof Number) { 429 | return ((Number) value).floatValue(); 430 | } 431 | final String valueStr = toStr(value, null); 432 | if (StringUtils.isEmpty(valueStr)) { 433 | return defaultValue; 434 | } 435 | try { 436 | return Float.parseFloat(valueStr.trim()); 437 | } catch (Exception e) { 438 | return defaultValue; 439 | } 440 | } 441 | 442 | /** 443 | * 转换为Float
444 | * 如果给定的值为空,或者转换失败,返回默认值null
445 | * 转换失败不会报错 446 | * 447 | * @param value 被转换的值 448 | * @return 结果 449 | */ 450 | public static Float toFloat(Object value) { 451 | return toFloat(value, null); 452 | } 453 | 454 | /** 455 | * 转换为boolean
456 | * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
457 | * 转换失败不会报错 458 | * 459 | * @param value 被转换的值 460 | * @param defaultValue 转换错误时的默认值 461 | * @return 结果 462 | */ 463 | public static Boolean toBool(Object value, Boolean defaultValue) { 464 | if (value == null) { 465 | return defaultValue; 466 | } 467 | if (value instanceof Boolean) { 468 | return (Boolean) value; 469 | } 470 | String valueStr = toStr(value, null); 471 | if (StringUtils.isEmpty(valueStr)) { 472 | return defaultValue; 473 | } 474 | valueStr = valueStr.trim().toLowerCase(); 475 | switch (valueStr) { 476 | case "true": 477 | return true; 478 | case "false": 479 | return false; 480 | case "yes": 481 | return true; 482 | case "ok": 483 | return true; 484 | case "no": 485 | return false; 486 | case "1": 487 | return true; 488 | case "0": 489 | return false; 490 | default: 491 | return defaultValue; 492 | } 493 | } 494 | 495 | /** 496 | * 转换为boolean
497 | * 如果给定的值为空,或者转换失败,返回默认值null
498 | * 转换失败不会报错 499 | * 500 | * @param value 被转换的值 501 | * @return 结果 502 | */ 503 | public static Boolean toBool(Object value) { 504 | return toBool(value, null); 505 | } 506 | 507 | /** 508 | * 转换为Enum对象
509 | * 如果给定的值为空,或者转换失败,返回默认值
510 | * 511 | * @param clazz Enum的Class 512 | * @param value 值 513 | * @param defaultValue 默认值 514 | * @return Enum 515 | */ 516 | public static > E toEnum(Class clazz, Object value, E defaultValue) { 517 | if (value == null) { 518 | return defaultValue; 519 | } 520 | if (clazz.isAssignableFrom(value.getClass())) { 521 | @SuppressWarnings("unchecked") 522 | E myE = (E) value; 523 | return myE; 524 | } 525 | final String valueStr = toStr(value, null); 526 | if (StringUtils.isEmpty(valueStr)) { 527 | return defaultValue; 528 | } 529 | try { 530 | return Enum.valueOf(clazz, valueStr); 531 | } catch (Exception e) { 532 | return defaultValue; 533 | } 534 | } 535 | 536 | /** 537 | * 转换为Enum对象
538 | * 如果给定的值为空,或者转换失败,返回默认值null
539 | * 540 | * @param clazz Enum的Class 541 | * @param value 值 542 | * @return Enum 543 | */ 544 | public static > E toEnum(Class clazz, Object value) { 545 | return toEnum(clazz, value, null); 546 | } 547 | 548 | /** 549 | * 转换为BigInteger
550 | * 如果给定的值为空,或者转换失败,返回默认值
551 | * 转换失败不会报错 552 | * 553 | * @param value 被转换的值 554 | * @param defaultValue 转换错误时的默认值 555 | * @return 结果 556 | */ 557 | public static BigInteger toBigInteger(Object value, BigInteger defaultValue) { 558 | if (value == null) { 559 | return defaultValue; 560 | } 561 | if (value instanceof BigInteger) { 562 | return (BigInteger) value; 563 | } 564 | if (value instanceof Long) { 565 | return BigInteger.valueOf((Long) value); 566 | } 567 | final String valueStr = toStr(value, null); 568 | if (StringUtils.isEmpty(valueStr)) { 569 | return defaultValue; 570 | } 571 | try { 572 | return new BigInteger(valueStr); 573 | } catch (Exception e) { 574 | return defaultValue; 575 | } 576 | } 577 | 578 | /** 579 | * 转换为BigInteger
580 | * 如果给定的值为空,或者转换失败,返回默认值null
581 | * 转换失败不会报错 582 | * 583 | * @param value 被转换的值 584 | * @return 结果 585 | */ 586 | public static BigInteger toBigInteger(Object value) { 587 | return toBigInteger(value, null); 588 | } 589 | 590 | /** 591 | * 转换为BigDecimal
592 | * 如果给定的值为空,或者转换失败,返回默认值
593 | * 转换失败不会报错 594 | * 595 | * @param value 被转换的值 596 | * @param defaultValue 转换错误时的默认值 597 | * @return 结果 598 | */ 599 | public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) { 600 | if (value == null) { 601 | return defaultValue; 602 | } 603 | if (value instanceof BigDecimal) { 604 | return (BigDecimal) value; 605 | } 606 | if (value instanceof Long) { 607 | return new BigDecimal((Long) value); 608 | } 609 | if (value instanceof Double) { 610 | return new BigDecimal((Double) value); 611 | } 612 | if (value instanceof Integer) { 613 | return new BigDecimal((Integer) value); 614 | } 615 | final String valueStr = toStr(value, null); 616 | if (StringUtils.isEmpty(valueStr)) { 617 | return defaultValue; 618 | } 619 | try { 620 | return new BigDecimal(valueStr); 621 | } catch (Exception e) { 622 | return defaultValue; 623 | } 624 | } 625 | 626 | /** 627 | * 转换为BigDecimal
628 | * 如果给定的值为空,或者转换失败,返回默认值
629 | * 转换失败不会报错 630 | * 631 | * @param value 被转换的值 632 | * @return 结果 633 | */ 634 | public static BigDecimal toBigDecimal(Object value) { 635 | return toBigDecimal(value, null); 636 | } 637 | 638 | /** 639 | * 将对象转为字符串
640 | * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 641 | * 642 | * @param obj 对象 643 | * @return 字符串 644 | */ 645 | public static String utf8Str(Object obj) { 646 | return str(obj, CharsetKit.CHARSET_UTF_8); 647 | } 648 | 649 | /** 650 | * 将对象转为字符串
651 | * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 652 | * 653 | * @param obj 对象 654 | * @param charsetName 字符集 655 | * @return 字符串 656 | */ 657 | public static String str(Object obj, String charsetName) { 658 | return str(obj, Charset.forName(charsetName)); 659 | } 660 | 661 | /** 662 | * 将对象转为字符串
663 | * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 664 | * 665 | * @param obj 对象 666 | * @param charset 字符集 667 | * @return 字符串 668 | */ 669 | public static String str(Object obj, Charset charset) { 670 | if (null == obj) { 671 | return null; 672 | } 673 | 674 | if (obj instanceof String) { 675 | return (String) obj; 676 | } else if (obj instanceof byte[] || obj instanceof Byte[]) { 677 | return str((Byte[]) obj, charset); 678 | } else if (obj instanceof ByteBuffer) { 679 | return str((ByteBuffer) obj, charset); 680 | } 681 | return obj.toString(); 682 | } 683 | 684 | /** 685 | * 将byte数组转为字符串 686 | * 687 | * @param bytes byte数组 688 | * @param charset 字符集 689 | * @return 字符串 690 | */ 691 | public static String str(byte[] bytes, String charset) { 692 | return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset)); 693 | } 694 | 695 | /** 696 | * 解码字节码 697 | * 698 | * @param data 字符串 699 | * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 700 | * @return 解码后的字符串 701 | */ 702 | public static String str(byte[] data, Charset charset) { 703 | if (data == null) { 704 | return null; 705 | } 706 | 707 | if (null == charset) { 708 | return new String(data); 709 | } 710 | return new String(data, charset); 711 | } 712 | 713 | /** 714 | * 将编码的byteBuffer数据转换为字符串 715 | * 716 | * @param data 数据 717 | * @param charset 字符集,如果为空使用当前系统字符集 718 | * @return 字符串 719 | */ 720 | public static String str(ByteBuffer data, String charset) { 721 | if (data == null) { 722 | return null; 723 | } 724 | 725 | return str(data, Charset.forName(charset)); 726 | } 727 | 728 | /** 729 | * 将编码的byteBuffer数据转换为字符串 730 | * 731 | * @param data 数据 732 | * @param charset 字符集,如果为空使用当前系统字符集 733 | * @return 字符串 734 | */ 735 | public static String str(ByteBuffer data, Charset charset) { 736 | if (null == charset) { 737 | charset = Charset.defaultCharset(); 738 | } 739 | return charset.decode(data).toString(); 740 | } 741 | 742 | // ----------------------------------------------------------------------- 全角半角转换 743 | 744 | /** 745 | * 半角转全角 746 | * 747 | * @param input String. 748 | * @return 全角字符串. 749 | */ 750 | public static String toSBC(String input) { 751 | return toSBC(input, null); 752 | } 753 | 754 | /** 755 | * 半角转全角 756 | * 757 | * @param input String 758 | * @param notConvertSet 不替换的字符集合 759 | * @return 全角字符串. 760 | */ 761 | public static String toSBC(String input, Set notConvertSet) { 762 | char c[] = input.toCharArray(); 763 | for (int i = 0; i < c.length; i++) { 764 | if (null != notConvertSet && notConvertSet.contains(c[i])) { 765 | // 跳过不替换的字符 766 | continue; 767 | } 768 | 769 | if (c[i] == ' ') { 770 | c[i] = '\u3000'; 771 | } else if (c[i] < '\177') { 772 | c[i] = (char) (c[i] + 65248); 773 | 774 | } 775 | } 776 | return new String(c); 777 | } 778 | 779 | /** 780 | * 全角转半角 781 | * 782 | * @param input String. 783 | * @return 半角字符串 784 | */ 785 | public static String toDBC(String input) { 786 | return toDBC(input, null); 787 | } 788 | 789 | /** 790 | * 替换全角为半角 791 | * 792 | * @param text 文本 793 | * @param notConvertSet 不替换的字符集合 794 | * @return 替换后的字符 795 | */ 796 | public static String toDBC(String text, Set notConvertSet) { 797 | char c[] = text.toCharArray(); 798 | for (int i = 0; i < c.length; i++) { 799 | if (null != notConvertSet && notConvertSet.contains(c[i])) { 800 | // 跳过不替换的字符 801 | continue; 802 | } 803 | 804 | if (c[i] == '\u3000') { 805 | c[i] = ' '; 806 | } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { 807 | c[i] = (char) (c[i] - 65248); 808 | } 809 | } 810 | String returnString = new String(c); 811 | 812 | return returnString; 813 | } 814 | 815 | /** 816 | * 数字金额大写转换 先写个完整的然后将如零拾替换成零 817 | * 818 | * @param n 数字 819 | * @return 中文大写数字 820 | */ 821 | public static String digitUppercase(double n) { 822 | String[] fraction = {"角", "分"}; 823 | String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; 824 | String[][] unit = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}}; 825 | 826 | String head = n < 0 ? "负" : ""; 827 | n = Math.abs(n); 828 | 829 | String s = ""; 830 | for (int i = 0; i < fraction.length; i++) { 831 | s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", ""); 832 | } 833 | if (s.length() < 1) { 834 | s = "整"; 835 | } 836 | int integerPart = (int) Math.floor(n); 837 | 838 | for (int i = 0; i < unit[0].length && integerPart > 0; i++) { 839 | String p = ""; 840 | for (int j = 0; j < unit[1].length && n > 0; j++) { 841 | p = digit[integerPart % 10] + unit[1][j] + p; 842 | integerPart = integerPart / 10; 843 | } 844 | s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s; 845 | } 846 | return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整"); 847 | } 848 | } 849 | --------------------------------------------------------------------------------