手写代码生成工具实现类似Mybatis-Plus的效果-----02
zhezhongyun 2025-05-14 18:25 22 浏览
package com.alatus.builder;
import com.alatus.Entity.FieldInfo;
import com.alatus.Entity.TableInfo;
import com.alatus.constant.Constants;
import com.alatus.utils.PropertiesUtils;
import com.alatus.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class TableBuilder {
private static Connection CONNECTION = null;
private static Logger LOGGER = LoggerFactory.getLogger(TableBuilder.class);
private static String SHOW_TABLE_STATUS = "show table status";
private static String SHOW_TABLE_FIELDS = "show full fields from %s";
static{
String driverName = PropertiesUtils.getValue("db.driver.name");
String url = PropertiesUtils.getValue("db.url");
String username = PropertiesUtils.getValue("db.username");
String password = PropertiesUtils.getValue("db.password");
try {
Class.forName(driverName);
CONNECTION = DriverManager.getConnection(url, username, password);
LOGGER.info("数据库连接成功");
} catch (ClassNotFoundException e) {
LOGGER.error("数据库驱动加载失败: {}", e.getMessage(), e);
} catch (SQLException e) {
LOGGER.error("数据库连接失败: {}", e.getMessage(), e);
}
}
public static void getTables(){
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<TableInfo> tableInfoList = new ArrayList<>();
try{
preparedStatement = CONNECTION.prepareStatement(SHOW_TABLE_STATUS);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
String tableName = resultSet.getString("name");
String comment = resultSet.getString("comment");
TableInfo tableInfo = new TableInfo();
tableInfo.setTableName(tableName);
tableInfo.setComment(comment);
String beanName = tableName;
if(Constants.IGNORE_TABLE_PREFIX){
beanName = tableName.substring(tableName.indexOf("_")+1);
}
beanName = processFields(beanName,true);
tableInfo.setBeanName(beanName);
tableInfo.setBeanParamName(beanName+Constants.SUFFIX_BEAN_PARAM);
tableInfo.setFieldList(getFieldInfo(tableInfo));
tableInfoList.add(tableInfo);
}
}
catch (SQLException e){
LOGGER.error("获取表失败: {}", e.getMessage(), e);
}
finally {
LOGGER.info("关闭数据库连接");
// 关闭 ResultSet
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
LOGGER.error("关闭ResultSet失败: {}", e.getMessage(), e);
}
}
// 关闭 PreparedStatement
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
LOGGER.error("关闭PreparedStatement失败: {}", e.getMessage(), e);
}
}
// 关闭 Connection
if (CONNECTION != null) {
try {
CONNECTION.close();
} catch (SQLException e) {
LOGGER.error("关闭Connection失败: {}", e.getMessage(), e);
}
}
}
}
private static List<FieldInfo> getFieldInfo(TableInfo tableInfo){
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<FieldInfo> fieldInfoList = new ArrayList<>();
try{
preparedStatement = CONNECTION.prepareStatement(String.format(SHOW_TABLE_FIELDS,tableInfo.getTableName()));
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
String field = resultSet.getString("field");
String type = resultSet.getString("type");
String comment = resultSet.getString("comment");
String extra = resultSet.getString("extra");
if(type.indexOf("(")>0){
// 从第一个字母开始,到(出现的位置截串,取得不要符号的类型名称
type = type.substring(0,type.indexOf("("));
}
String propertyName = processFields(field,false);
FieldInfo fieldInfo = new FieldInfo();
fieldInfo.setFieldName(field);
fieldInfo.setComment(comment);
fieldInfo.setSqlType(type);
fieldInfo.setIsAutoIncrement("auto_increment".equalsIgnoreCase(extra));
fieldInfo.setPropertyName(propertyName);
fieldInfoList.add(fieldInfo);
}
}
catch (SQLException e){
LOGGER.error("获取表失败: {}", e.getMessage(), e);
}
finally {
LOGGER.info("关闭数据库连接");
// 关闭 ResultSet
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
LOGGER.error("关闭ResultSet失败: {}", e.getMessage(), e);
}
}
// 关闭 PreparedStatement
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
LOGGER.error("关闭PreparedStatement失败: {}", e.getMessage(), e);
}
}
return fieldInfoList;
}
}
private static String processFields(String fieldName,Boolean upperCase){
StringBuilder builder = new StringBuilder();
String[] fields = fieldName.split("_");
builder.append(upperCase? StringUtils.firstCharToUpperCase(fields[0]):fields[0]);
for (int i = 1; i < fields.length; i++) {
builder.append(StringUtils.firstCharToUpperCase(fields[i]));
}
return builder.toString();
}
private static String processJavaType(String type) {
if (ArrayUtils.contains(Constants.SQL_INTEGER_TYPE, type)) {
return "Integer";
} else if (ArrayUtils.contains(Constants.SOL_LONG_TYPE, type)) {
return "Long";
} else if (ArrayUtils.contains(Constants.SQL_STRING_TYPE, type)) {
return "String";
} else if (ArrayUtils.contains(Constants.SOL_DATE_TIME_TYPES, type) || ArrayUtils.contains(Constants.SOL_DATE_TYPES, type)) {
return "Date";
} else if (ArrayUtils.contains(Constants.SQL_DECIMAL_TYPE, type)) {
return "BigDecimal";
} else {
LOGGER.error("不支持的数据类型: {}", type);
return null;
}
}
}
package com.alatus.constant;
import com.alatus.utils.PropertiesUtils;
public class Constants {
public static Boolean IGNORE_TABLE_PREFIX;
public static String SUFFIX_BEAN_PARAM;
static{
IGNORE_TABLE_PREFIX = Boolean.valueOf(PropertiesUtils.getValue("ignore.table.prefix"));
SUFFIX_BEAN_PARAM = PropertiesUtils.getValue("suffix.bean.param");
}
public final static String[] SOL_DATE_TIME_TYPES = new String[] {"datetime", "timestamp"};
public final static String[] SOL_DATE_TYPES = new String[] {"date"};
public static final String[] SQL_DECIMAL_TYPE = new String[] {"decimal", "double", "float"};
public static final String[] SQL_STRING_TYPE = new String[] {"char", "varchar", "text", "mediumtext", "longtext"};
// Integer
public static final String[] SQL_INTEGER_TYPE = new String[] {"int", "tinyint"};
// Long
public static final String[] SOL_LONG_TYPE = new String[] {"bigint"};
}
package com.alatus;
import com.alatus.builder.TableBuilder;
public class GeneratorApplication {
public static void main(String[] args) {
TableBuilder.getTables();
}
}
package com.alatus.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
public class PropertiesUtils {
private static Properties properties = new Properties();
private static Map<String, String> propertiesMap = new ConcurrentHashMap<>();
private static Logger LOGGER = LoggerFactory.getLogger(PropertiesUtils.class);
static {
InputStream inputStream = null;
try{
// 典中典资源加载
inputStream = PropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties");
properties.load(inputStream);
// 我想起来了,这个Properties对象是JAVA提供的特殊Map结构
Iterator<Object> iterator = properties.keySet().iterator();
// 所以也是自带KV结构的,因此我只要遍历它的KeySet,取出每一个Key,再把对应的Key和对应的Value放入Map中
// 就可以实现完整的加载properties中的数据了
while(iterator.hasNext()){
String key = (String) iterator.next();
propertiesMap.put(key,properties.getProperty(key));
}
}catch (Exception e){
LOGGER.error("加载配置文件失败: {}", e.getMessage(), e);
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
LOGGER.error("关闭资源失败: {}", e.getMessage(), e);
}
}
}
}
public static String getValue(String key){
// 因为我们的配置信息是静态读取的,所以直接返回Map中的值即可
return propertiesMap.get(key);
}
}
db.driver.name=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/ourapp?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
db.username=root
db.password=abc123
ignore.table.prefix=true
suffix.bean.param=Param
相关推荐
- 一篇文章带你了解SVG 渐变知识(svg动画效果)
-
渐变是一种从一种颜色到另一种颜色的平滑过渡。另外,可以把多个颜色的过渡应用到同一个元素上。SVG渐变主要有两种类型:(Linear,Radial)。一、SVG线性渐变<linearGradie...
- Vue3 实战指南:15 个高效组件开发技巧解析
-
Vue.js作为一款流行的JavaScript框架,在前端开发领域占据着重要地位。Vue3的发布,更是带来了诸多令人兴奋的新特性和改进,让开发者能够更高效地构建应用程序。今天,我们就来深入探讨...
- CSS渲染性能优化(低阻抗喷油器阻值一般为多少欧)
-
在当今快节奏的互联网环境中,网页加载速度直接影响用户体验和业务转化率。页面加载时间每增加100毫秒,就会导致显著的流量和收入损失。作为前端开发的重要组成部分,CSS的渲染性能优化不容忽视。为什么CSS...
- 前端面试题-Vue 项目中,你做过哪些性能优化?
-
在Vue项目中,以下是我在生产环境中实践过且用户反馈较好的性能优化方案,整理为分类要点:一、代码层面优化1.代码分割与懒加载路由懒加载:使用`()=>import()`动态导入组件,结...
- 如何通过JavaScript判断Web页面按钮是否置灰?
-
在JavaScript语言中判断Web页面按钮是否置灰(禁用状态),可以通过以下几种方式实现,其具体情形取决于按钮的禁用方式(原生disabled属性或CSS样式控制):一、检查原生dis...
- 「图片显示移植-1」 尝试用opengl/GLFW显示图片
-
GLFW【https://www.glfw.org】调用了opengl来做图形的显示。我最近需要用opengl来显示图像,不能使用opencv等库。看了一个glfw的官网,里面有github:http...
- 大模型实战:Flask+H5三件套实现大模型基础聊天界面
-
本文使用Flask和H5三件套(HTML+JS+CSS)实现大模型聊天应用的基本方式话不多说,先贴上实现效果:流式输出:思考输出:聊天界面模型设置:模型设置会话切换:前言大模型的聊天应用从功能...
- ae基础知识(二)(ae必学知识)
-
hi,大家好,我今天要给大家继续分享的还是ae的基础知识,今天主要分享的就是关于ae的路径文字制作步骤(时间关系没有截图)、动态文字的制作知识、以及ae特效的扭曲的一些基本操作。最后再次复习一下ae的...
- YSLOW性能测试前端调优23大规则(二十一)---避免过滤器
-
AlphalmageLoader过滤器是IE浏览器专有的一个关于图片的属性,主要是为了解决半透明真彩色的PNG显示问题。AlphalmageLoader的语法如下:filter:progid:DX...
- Chrome浏览器的渲染流程详解(chrome预览)
-
我们来详细介绍一下浏览器的**渲染流程**。渲染流程是浏览器将从网络获取到的HTML、CSS和JavaScript文件,最终转化为用户屏幕上可见的、可交互的像素画面的过程。它是一个复杂但高度优...
- 在 WordPress 中如何设置背景色透明度?
-
最近开始写一些WordPress专业的知识,阅读数奇低,然后我发一些微信昵称技巧,又说我天天发这些小学生爱玩的玩意,写点文章真不容易。那我两天发点专业的东西,两天发点小学生的东西,剩下三天我看着办...
- manim 数学动画之旅--图形样式(数学图形绘制)
-
manim绘制图形时,除了上一节提到的那些必需的参数,还有一些可选的参数,这些参数可以控制图形显示的样式。绘制各类基本图形(点,线,圆,多边形等)时,每个图形都有自己的默认的样式,比如上一节的图形,...
- Web页面如此耗电!到了某种程度,会是大损失
-
现在用户上网大多使用移动设备或者笔记本电脑。对这两者来说,电池寿命都很重要。在这篇文章里,我们将讨论影响电池寿命的因素,以及作为一个web开发者,我们如何让网页耗电更少,以便用户有更多时间来关注我们的...
- 11.mxGraph的mxCell和Styles样式(graph style)
-
3.1.3mxCell[翻译]mxCell是顶点和边的单元对象。mxCell复制了模型中可用的许多功能。使用上的关键区别是,使用模型方法会创建适当的事件通知和撤销,而使用单元进行更改时没有更改记...
- 按钮重复点击:这“简单”问题,为何难住大半面试者与开发者?
-
在前端开发中,按钮重复点击是一个看似不起眼,实则非常普遍且容易引发线上事故的问题。想象一下:提交表单时,因为网络卡顿或手抖,重复点击导致后端创建了多条冗余数据…这些场景不仅影响用户体验,更可能造成实...
- 一周热门
- 最近发表
- 标签列表
-
- HTML 教程 (33)
- HTML 简介 (35)
- HTML 实例/测验 (32)
- HTML 测验 (32)
- JavaScript 和 HTML DOM 参考手册 (32)
- HTML 拓展阅读 (30)
- HTML文本框样式 (31)
- HTML滚动条样式 (34)
- HTML5 浏览器支持 (33)
- HTML5 新元素 (33)
- HTML5 WebSocket (30)
- HTML5 代码规范 (32)
- HTML5 标签 (717)
- HTML5 标签 (已废弃) (75)
- HTML5电子书 (32)
- HTML5开发工具 (34)
- HTML5小游戏源码 (34)
- HTML5模板下载 (30)
- HTTP 状态消息 (33)
- HTTP 方法:GET 对比 POST (33)
- 键盘快捷键 (35)
- 标签 (226)
- HTML button formtarget 属性 (30)
- CSS 水平对齐 (Horizontal Align) (30)
- opacity 属性 (32)