数据库表到java类转换工具
//该工具类可以实现:给定一个指定的数据库表名,即可自动生成对应的java实体类
package com.iamzken.utils; import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector; public class DB2JavaConvertor {
private Connection connection;
private PreparedStatement UserQuery;
/*mysql url的连接字符串*/
private static String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useOldAliasMetadataBehavior=true";
//账号
private static String user = "root";
//密码
private static String password = "";
private Vector<String> vector = new Vector<String>();
//mysql jdbc的java包驱动字符串
private String driverClassName = "com.mysql.jdbc.Driver";
//数据库中的表名
String table = "teacher";
//数据库的列名称
private String[] colnames; // 列名数组
//列名类型数组
private String[] colTypes;
public DB2JavaConvertor(){
try {//驱动注册
Class.forName(driverClassName);
if (connection == null || connection.isClosed())
//获得链接
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
System.out.println("Oh,not");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Oh,not");
}
} public Connection getConnection() {
return connection;
}
public void setConnection(Connection connection) {
this.connection = connection;
} public void doAction(){
String sql = "select * from "+table;
try {
PreparedStatement statement = connection.prepareStatement(sql);
//获取数据库的元数据
ResultSetMetaData metadata = statement.getMetaData();
//数据库的字段个数
int len = metadata.getColumnCount();
//字段名称
colnames = new String[len+1];
//字段类型 --->已经转化为java中的类名称了
colTypes = new String[len+1];
for(int i= 1;i<=len;i++){
//System.out.println(metadata.getColumnName(i)+":"+metadata.getColumnTypeName(i)+":"+sqlType2JavaType(metadata.getColumnTypeName(i).toLowerCase())+":"+metadata.getColumnDisplaySize(i));
//metadata.getColumnDisplaySize(i);
colnames[i] = metadata.getColumnName(i); //获取字段名称
colTypes[i] = sqlType2JavaType(metadata.getColumnTypeName(i)); //获取字段类型
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* mysql的字段类型转化为java的类型*/
private String sqlType2JavaType(String sqlType) { if(sqlType.equalsIgnoreCase("bit")){
return "boolean";
}else if(sqlType.equalsIgnoreCase("tinyint")){
return "byte";
}else if(sqlType.equalsIgnoreCase("smallint")){
return "short";
}else if(sqlType.equalsIgnoreCase("INTEGER")){
return "int";
}else if(sqlType.equalsIgnoreCase("bigint")){
return "long";
}else if(sqlType.equalsIgnoreCase("float")){
return "float";
}else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
|| sqlType.equalsIgnoreCase("smallmoney")){
return "double";
}else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
|| sqlType.equalsIgnoreCase("text")){
return "String";
}else if(sqlType.equalsIgnoreCase("datetime") ||sqlType.equalsIgnoreCase("date")){
return "java.util.Date";
}else if(sqlType.equalsIgnoreCase("image")){
return "Blod";
} return null;
}
/*获取整个类的字符串并且输出为java文件
* */
public StringBuffer getClassStr(){
String className = table.substring(0,1).toUpperCase()+table.substring(1);
//输出的类字符串
StringBuffer str = new StringBuffer("");
//获取表类型和表名的字段名
this.doAction();
//校验
if(null == colnames && null == colTypes) return null; str.append(this.getClass().getPackage()+";\r\n\r\n");
//拼接
str.append("public class "+className+" {\r\n");
//拼接属性
for(int index=1; index < colnames.length ; index++){
str.append(getAttrbuteString(colnames[index],colTypes[index]));
}
//拼接get,Set方法
for(int index=1; index < colnames.length ; index++){
str.append(getGetMethodString(colnames[index],colTypes[index]));
str.append(getSetMethodString(colnames[index],colTypes[index]));
}
str.append("}\r\n");
//输出到文件中
String s1 = DB2JavaConvertor.class.getPackage().getName().replace(".", "\\");
String s2 = "src"+File.separator+"main"+File.separator+"java"+File.separator+s1;
String s3 = System.getProperty("user.dir")+File.separator+s2;
File file = new File(s3);
if(!file.exists()){
file.mkdirs();
}
BufferedWriter write = null; try {
write = new BufferedWriter(new FileWriter(new File(s3+File.separator+className+".java")));
write.write(str.toString());
write.close();
} catch (IOException e) { e.printStackTrace();
if (write != null)
try {
write.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return str;
}
/*
* 获取字段字符串*/
public StringBuffer getAttrbuteString(String name, String type) {
if(!check(name,type)) {
System.out.println("类中有属性或者类型为空");
return null;
};
String format = String.format(" private %s %s;\n\r", new String[]{type,name});
return new StringBuffer(format);
}
/*
* 校验name和type是否合法*/
public boolean check(String name, String type) {
if("".equals(name) || name == null || name.trim().length() ==0){
return false;
}
if("".equals(type) || type == null || type.trim().length() ==0){
return false;
}
return true; }
/*
* 获取get方法字符串*/
private StringBuffer getGetMethodString(String name, String type) {
if(!check(name,type)) {
System.out.println("类中有属性或者类型为空");
return null;
};
String Methodname = "get"+GetTuoFeng(name);
String format = String.format(" public %s %s(){\n\r", new Object[]{type,Methodname});
format += String.format(" return this.%s;\r\n", new Object[]{name});
format += " }\r\n";
return new StringBuffer(format);
}
//将名称首字符大写
private String GetTuoFeng(String name) {
name = name.trim();
if(name.length() > 1){
name = name.substring(0, 1).toUpperCase()+name.substring(1);
}else
{
name = name.toUpperCase();
}
return name;
}
/*
* 获取字段的get方法字符串*/
private Object getSetMethodString(String name, String type) {
if(!check(name,type)) {
System.out.println("类中有属性或者类型为空");
return null;
};
String Methodname = "set"+GetTuoFeng(name);
String format = String.format(" public void %s(%s %s){\n\r", new Object[]{Methodname,type,name});
format += String.format(" this.%s = %s;\r\n", new Object[]{name,name});
format += " }\r\n";
return new StringBuffer(format);
} public static void main(String[] args) throws IOException {
DB2JavaConvertor bean = new DB2JavaConvertor();
System.err.println(bean.getClassStr());
//System.out.println(ReflectBean.class.getPackage());
//System.out.println(ReflectBean.class.getPackage().getName());
//System.out.println(ReflectBean.class.getResource("").getPath());
// File directory = new File("");//参数为空
// String courseFile = directory.getCanonicalPath() ;
// System.out.println(courseFile);
//
//
// File f = new File(ReflectBean.class.getResource("").getPath());
// System.out.println(f);
//
//
// URL xmlpath = ReflectBean.class.getClassLoader().getResource("");
// System.out.println(xmlpath);
//
// String s1 = directory.getAbsolutePath();
// System.out.println(s1);
/* String s3 = ReflectBean.class.getPackage().getName().replace(".", "\\");
String s2 = System.getProperty("user.dir")+File.separator+s3;
System.out.println(s2);*/
} }
数据库表到java类转换工具的更多相关文章
- Java逆向工程(数据库表生成java类)
说起来倒是挺简单的,就是听着名字感觉挺高大上.逆向工程方式有很多,比如mybatis就提供了一个这样的工具mybatis-genderator,这个我反正是没用过只是听说过,以前在公司都是用公司写好的 ...
- 我的Android进阶之旅------>Java文件大小转换工具类 (B,KB,MB,GB,TB,PB之间的大小转换)
Java文件大小转换工具类 (B,KB,MB,GB,TB,PB之间的大小转换) 有时候要做出如下所示的展示文件大小的效果时候,需要对文件大小进行转换,然后再进行相关的代码逻辑编写. 下面是一个Java ...
- Oracle数据库中调用Java类开发存储过程、函数的方法
Oracle数据库中调用Java类开发存储过程.函数的方法 时间:2014年12月24日 浏览:5538次 oracle数据库的开发非常灵活,不仅支持最基本的SQL,而且还提供了独有的PL/SQL, ...
- django根据已有数据库表生成model类
django根据已有数据库表生成model类 创建一个Django项目 django-admin startproject 'xxxx' 修改setting文件,在setting里面设置你要连接的数据 ...
- EntityUtils MapStruct BeanCopier 数据实体类转换工具 DO BO VO DTO 附视频
一.序言 在实际项目开发过程中,总有数据实体类互相转换的需求,DO.BO.VO.DTO等数据模型转换经常发生.今天推荐几个好用的实体类转换工具,分别是EntityUtils MapStruct Bea ...
- IDEA快速生成数据库表的实体类
IDEA连接数据库 IDEA右边侧栏有个DataSource,可以通过这个来连接数据库,我们先成功连接数据库 点击进入后填写数据库进行连接,注意记得一定要去Test Connection 确保正常连接 ...
- 如何通过java反射将数据库表生成实体类?
首先有几点声明: 1.代码是在别人的基础进行改写的: 2.大家有什么改进的意见可以告诉我,也可以自己改好共享给其他人: 3.刚刚毕业,水平有限,肯定有许多不足之处: 4.希望刚刚学习java的同学能有 ...
- java json转换工具类
在java项目中,通常会用到json类型的转换,常常需要对 json字符串和对象进行相互转换. 在制作自定义的json转换类之前,先引入以下依赖 <!--json相关工具--><de ...
- sts使用mybatis插件直接生成数据库表的mapper类及配置文件
首先点击help------>Eclipse Marketplace----->在find中搜索mybatis下面图片的第一个 点击installed 还需要一个配置文件generator ...
- mybatise插件反向生成数据库表相关Java代码
1.下载相关jar包https://github.com/mybatis/generator/releases 2.配置xml文件 <?xml version="1.0" e ...
随机推荐
- 苹果iOS 17正式版来了:iPhone X/8系列等机型无缘
据媒体报道,苹果会在9月13日凌晨1点发布iPhone 15系列新品,该机出厂预装iOS 17正式版系统. 在iPhone 15系列之后,苹果会向老机型推送iOS 17正式版更新.据爆料,苹果将会在9 ...
- 从TF-IDF 到BM25, BM25+,一文彻底理解文本相关度
相关性描述的是⼀个⽂档和查询语句匹配的程度.我们从搜索引擎召回时,肯定希望召回相关性高的数据,那么如何来量化相关度呢. 首先,我们定义,一个文档doc,由多个词语 term 组成. 最早,通过最简单的 ...
- 小知识:后台执行Oracle创建索引免受会话中断影响
因为客户环境的堡垒机经常会莫名的断开连接,也不是简单的超时,因为有时候即使你一直在操作,也可能会断. 这样对于操作一些耗时长且中途中断可能会导致异常的操作就很危险,而最简单的避免方法就是将其写到脚本中 ...
- 【译】介绍 MSTest Runner – CLI、Visual Studio 等
原文 | Amaury Levé, Marco Rossignoli, Jakub Jareš 翻译 | 郑子铭 我们很高兴推出 MSTest runner,这是一个用于 MSTest 测试的新型轻量 ...
- Ubuntu22.04 将EFI启动分区迁移到另一块硬盘
机器上有两块硬盘, 一块已经安装了Win10, 另一块新装Ubuntu22.04, 在新硬盘上划分分区的时候, 有分出256M给 BOOT EFI, 但是安装的时候没注意, 启动分区不知道怎的跑到 W ...
- 子集 II
子集 II 给定一个可能包含重复元素的整数数组nums,返回该数组所有可能的子集(幂集). 说明:解集不能包含重复的子集. 示例 输入: [1,2,2] 输出: [ [2], [1], [1,2,2] ...
- flask+xlswriter+axios导出Excel
flask后端 starttime = request.json.get('starttime') endtime = request.json.get('endtime') # 根据时间查询数据库数 ...
- ~Keven_He的黑历史~
"先生,我认为文言文比白话文更加简洁" "请举例" "就好像沉鱼落雁这句成语不是比白话文更加简洁吗" "沉鱼落雁是四个字,该用白话 ...
- Oracle日期格式化问题:to_date(sysdate,'yyyy-MM-dd')与 to_date(to_char(sysdate,'yyyy-MM-dd'),'yyyy-MM-dd')区别
1.需求描述 对系统日期进行格式化,并仍保持日期类型 2.错误方法 直接使用to_date()实现 SELECT TO_DATE(SYSDATE,'YYYY-MM-DD') FROM DUAL; 这样 ...
- 项目打包setup.py(setuptools)
参考 https://www.cnblogs.com/dan-baishucaizi/p/13564333.html https://www.cnblogs.com/dan-baishucaizi/p ...