利用JAVA反射,读取数据库表名,自动生成对应实体类的操作
作者:保持丶零距离 时间:2024-01-14 23:58:29
本代码是利用java反射,读取数据库表自动根据表名生成实体类,数据库采用老牌SQLSERVER 2000,驱动为JTDS,其他数据库可根据情况自定修改。
代码中包含了大部分数据库类型与JAVA类型的转换,少数未包含进去的会在生成代码时打印出来,方面后期查找修改。
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 从数据库表反射出实体类,自动生成实体类
*
* @author Zero
*
*/
public class SqlHelper {
//基本数据配置
private String packageOutPath = "com.xxx.entity.system";// 指定实体生成所在包的路径
private String authorName = "Zero";// 作者名字
private String tablename = "xxx";// 表名
private String[] colnames; // 列名数组
private String[] colTypes; // 列名类型数组
private String version = "V0.01"; // 版本
private int[] colSizes; // 列名大小数组
private boolean f_util = false; // 是否需要导入包java.util.*
private boolean f_sql = false; // 是否需要导入包java.sql.*
private boolean f_lang = false; // 是否需要导入包java.sql.*
private String defaultPath = "/src/main/java/";
// 数据库连接
private static final String URL = "jdbc:jtds:sqlserver://192.168.29.128:1433/xxx";
private static final String NAME = "sa";
private static final String PASS = "xxx";
private static final String DRIVER = "net.sourceforge.jtds.jdbc.Driver";
/*
* 构造函数
*/
public SqlHelper() {
// 创建连接
Connection con;
// 查要生成实体类的表
String sql = "select * from " + tablename;
PreparedStatement pStemt = null;
try {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
con = DriverManager.getConnection(URL, NAME, PASS);
pStemt = con.prepareStatement(sql);
ResultSetMetaData rsmd = pStemt.getMetaData();
int size = rsmd.getColumnCount(); // 统计列
colnames = new String[size];
colTypes = new String[size];
colSizes = new int[size];
for (int i = 0; i < size; i++) {
colnames[i] = rsmd.getColumnName(i + 1);
colTypes[i] = rsmd.getColumnTypeName(i + 1);
//自动生成包配置
// if (colTypes[i].equalsIgnoreCase("datetime")) {
// f_util = true;
// }
if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")
|| colTypes[i].equalsIgnoreCase("datetime") || colTypes[i].equalsIgnoreCase("time")
|| colTypes[i].equalsIgnoreCase("date") || colTypes[i].equalsIgnoreCase("datetime2")) {
f_sql = true;
}
// if (colTypes[i].equalsIgnoreCase("int")) {
// f_lang = true;
// }
colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
}
String content = parse(colnames, colTypes, colSizes);
try {
File directory = new File("");
String path = this.getClass().getResource("").getPath();
System.out.println(path);
String outputPath = directory.getAbsolutePath() + this.defaultPath
+ this.packageOutPath.replace(".", "/") + "/" + initcap(tablename) + ".java";
System.out.println("执行完毕,生成路径为:"+outputPath);
FileWriter fw = new FileWriter(outputPath);
PrintWriter pw = new PrintWriter(fw);
pw.println(content);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
}
}
/**
* 功能:生成实体类主体代码
*
* @param colnames
* @param colTypes
* @param colSizes
* @return
*/
private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
StringBuffer sb = new StringBuffer();
// 生成package包路径
sb.append("package " + this.packageOutPath + ";\r\n");
// 判断是否导入工具包
if (f_util) {
sb.append("import java.util.Date;\r\n");
}
if (f_sql) {
sb.append("import java.sql.*;\r\n");
}
if (f_lang) {
sb.append("import java.lang.*;\r\n");
}
sb.append("\r\n");
// 注释部分
sb.append(" /**\r\n");
sb.append(" * @文件名称:" + this.tablename + ".java\r\n");
sb.append(" * @创建时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\r\n");
sb.append(" * @创 建 人:" + this.authorName + " \r\n");
sb.append(" * @文件描述:" + tablename + " 实体类\r\n");
sb.append(" * @文件版本:" + this.version + " \r\n");
sb.append(" */ \r\n");
// 实体部分
sb.append("\r\n\r\npublic class " + initcap(tablename) + "{\r\n");
processAllAttrs(sb);// 属性
processAllMethod(sb);// get set方法
sb.append("}\r\n");
// System.out.println(sb.toString());
return sb.toString();
}
/**
* 功能:生成所有属性
*
* @param sb
*/
private void processAllAttrs(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + ";\r\n");
}
}
/**
* 功能:生成所有方法
*
* @param sb
*/
private void processAllMethod(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
sb.append("\tpublic void set" + initcap(colnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " "
+ colnames[i] + "){\r\n");
sb.append("\tthis." + colnames[i] + "=" + colnames[i] + ";\r\n");
sb.append("\t}\r\n");
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(colnames[i]) + "(){\r\n");
sb.append("\t\treturn " + colnames[i] + ";\r\n");
sb.append("\t}\r\n");
}
}
/**
* 功能:将输入字符串的首字母改成大写
*
* @param str
* @return
*/
private String initcap(String str) {
char[] ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
return new String(ch);
}
/**
* 功能:获得列的数据类型
*
* @param sqlType
* @return
*/
private String sqlType2JavaType(String sqlType) {
if (sqlType.equalsIgnoreCase("bit")) {
return "Boolean";
} else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("money")
|| sqlType.equalsIgnoreCase("smallmoney") || sqlType.equalsIgnoreCase("numeric")
|| sqlType.equalsIgnoreCase("bigint")) {
return "Long";
} else if (sqlType.equalsIgnoreCase("float")) {
return "Double";
} else if (sqlType.equalsIgnoreCase("int") || sqlType.equalsIgnoreCase("int identity")) {
return "Integer";
} else if (sqlType.equalsIgnoreCase("image") || sqlType.equalsIgnoreCase("varbinary(max)")
|| sqlType.equalsIgnoreCase("varbinary") || sqlType.equalsIgnoreCase("udt")
|| sqlType.equalsIgnoreCase("timestamp") || sqlType.equalsIgnoreCase("binary")) {
return "Byte[]";
} else if (sqlType.equalsIgnoreCase("nchar") || sqlType.equalsIgnoreCase("nvarchar(max)")
|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nvarchar(ntext)")
|| sqlType.equalsIgnoreCase("uniqueidentifier") || sqlType.equalsIgnoreCase("xml")
|| sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("varchar(max)")
|| sqlType.equalsIgnoreCase("text") || sqlType.equalsIgnoreCase("varchar")) {
return "String";
} else if (sqlType.equalsIgnoreCase("real")) {
return "Float";
} else if (sqlType.equalsIgnoreCase("smallint") || sqlType.equalsIgnoreCase("tinyint")) {
return "Short";
} else if (sqlType.equalsIgnoreCase("date") || sqlType.equalsIgnoreCase("datetime")
|| sqlType.equalsIgnoreCase("time") || sqlType.equalsIgnoreCase("datetime2")) {
return "Date";
} else {
System.out.println("数据类型异常,类型为:" + sqlType);
}
return null;
}
/**
* 出口 TODO
*
* @param args
*/
public static void main(String[] args) {
new SqlHelper();
}
}
补充知识:java通过反射获取类名、属性名称以及@Table注解上的表名称
我就废话不多说了,大家还是直接看代码吧~
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author caizw
* @createDate 2018/2/8
* @description 反射工具类
*/
public class ReflectUtils {
/**
* 获取实体类主键
*
* @param clazz
* @return
*/
public static Field getIdField(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
Field item = null;
for (Field field : fields) {
Id id = field.getAnnotation(Id.class);
if (id != null) {
field.setAccessible(true);
item = field;
break;
}
}
if (item == null) {
Class<?> superclass = clazz.getSuperclass();
if (superclass != null) {
item = getIdField(superclass);
}
}
return item;
}
/**
* 根据主键名称获取实体类主键属性值
*
* @param clazz
* @param pkName
* @return
*/
public static Object getPkValueByName(Object clazz, String pkName) {
try {
String firstLetter = pkName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + pkName.substring(1);
Method method = clazz.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(clazz, new Object[]{});
return value;
} catch (Exception e) {
return null;
}
}
/**
* 通过反射将 class1不为空的值赋值给class2
*
* @param class1
* @param class2
* @throws Exception
*/
public static void reflectClass1ToClass2(Object class1, Object class2) throws Exception {
Field[] field = class1.getClass().getDeclaredFields();
for (int i = 0; i < field.length; i++) {
String name = field[i].getName();
if ("serialVersionUID".equals(name)) {
continue;
}
name = name.substring(0, 1).toUpperCase() + name.substring(1);
Method m1 = class1.getClass().getMethod("get" + name);
Object value = m1.invoke(class1);
if (value != null) {
Field f = field[i];
f.setAccessible(true);
f.set(class2, value);
}
}
}
/**
* 获取实体类 @Column 的其中一个属性名称
*
* @param clazz
* @return
*/
public static Map<String, String> getColumnName(Class<?> clazz) {
Map<String, String> map = new ConcurrentHashMap<>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Column.class)) {
/**
* 获取字段名
*/
Column declaredAnnotation = field.getDeclaredAnnotation(Column.class);
String column = declaredAnnotation.name();
map.put("fieldNames", field.getName());
map.put("column", column);
break;
}
}
return map;
}
/**
* 通过获取类上的@Table注解获取表名称
*
* @param clazz
* @return
*/
public static Map<String, String> getTableName(Class<?> clazz) {
Map<String, String> map = new ConcurrentHashMap<>();
Table annotation = clazz.getAnnotation(Table.class);
String name = annotation.name();
String className = clazz.getSimpleName();
map.put("tableName", name);
map.put("className", className);
return map;
}
}
来源:https://blog.csdn.net/zhum_sjz/article/details/80343549
标签:JAVA,反射,表名,实体类
0
投稿
猜你喜欢
linux下导入、导出mysql数据库命令的实现方法
2024-01-23 15:55:33
盗亦有道 Web2.0网站优秀模仿者逐个数
2007-09-11 19:46:00
SWFObject 2.1以上版本语法介绍
2024-04-10 10:49:18
python3调用百度翻译API实现实时翻译
2021-06-21 01:45:46
PyCharm安装配置Qt Designer+PyUIC图文教程
2022-10-21 08:44:46
基于go+vue实现的golang每日新闻数据浏览与检索平台(推荐)
2023-06-16 12:11:26
python 实现红包随机生成算法的简单实例
2022-07-07 17:32:48
使用numpy.mean() 计算矩阵均值方式
2021-12-17 03:55:53
针对google Chrome的 CSS hacks
2009-11-30 12:45:00
怎么让按钮更容易被点击
2007-08-22 09:07:00
Request.ServerVariables各参数说明集合
2008-11-25 18:49:00
Pycharm不同版本镜像源添加方法
2023-08-24 15:59:43
Web2.0 体验式网站设计的41个关键点
2008-08-10 17:49:00
使用Postman测试需要授权的接口问题
2022-10-18 15:14:23
《JavaScript DOM 编程艺术》读书笔记之JavaScript 简史
2024-04-10 16:13:23
详解vscode使用git所遇到的坑
2023-12-25 11:17:48
SQL server 自增ID--序号自动增加的字段操作
2024-01-29 03:51:55
Python3的urllib.parse常用函数小结(urlencode,quote,quote_plus,unquote,unquote_plus等)
2021-01-23 04:23:13
利用Go语言实现Raft日志同步
2024-03-15 02:55:20
实际应用:MySQL5存储过程编写
2008-11-11 12:25:00