数据库表到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 ...
随机推荐
- M2版Mac mini被京东杀到史低2888元!比苹果官网低1600
苹果跳水王M2版Mac mini又降价了. 根据京东官方百亿补贴频道显示,Mac mini 8+256GB入门版只要2888元了,比前不久的拼多多2959还低,刷新了这款电脑的史上最低价. 对比官网原 ...
- go中的 位预算,反码、补码、原码
https://baike.baidu.com/item/%E4%BD%8D%E8%BF%90%E7%AE%97/6888804 首先关于"位运算",看下百度百科就行了. 总结:在 ...
- Delphi中的注释,仅此一篇
在Pascal中,注释括在大括号中或带星号的圆括号中.Delphi 也认可C++ 风格的注释,即把注释放在双斜线后.例如: {this is a comment} (* this is another ...
- linux 搭建http文件服务器
1.安装httpd服务 yum -y install httpd 2.修改需要访问的文件路径 vi /etc/httpd/conf/httpd.conf ##默认是/var/www/html目录下的文 ...
- CF1795
A 先判断初始行不行,再模拟加入. B 题意:数轴上给定一些线段,和点 \(t\).问能否删去一些线段,使得 \(t\) 变成唯一的覆盖次数最多的点. 差分 + 贪心. C 有 \(n\) 杯水,\( ...
- NC50959 To the Max
题目链接 题目 题目描述 Given a two-dimensional array of positive and negative integers, a sub-rectangle is any ...
- 【OpenGL ES】光影(光照与阴影)效果
1 前言 Blinn改进的冯氏光照模型 中只展示了光照效果,本文将进一步展示阴影效果. 绘制阴影,需要用到深度纹理,即从光源角度看模型并绘制一张纹理图,纹理图的颜色代表了模型上的点离光源的深度 ...
- 高效发现和解决insert字段长度不够的报错
早上发现执行的PostgreSQL 存储过程报错,错误如下: 300-value too long for type character varying(100),一看就是表字段的长度太小,从提示看是 ...
- Java集合框架学习(十四) Iterator接口详解
Iterator接口介绍 public interface Iterator<E> iterator 用于迭代集合类型对象,例如: HashMap, ArrayList, LinkedLi ...
- error C2039: "function": 不是 "std" 的成员的解决方法
这个错误通过某度没找到合适的解决方案,故记录下来 其实如果使用 google 搜索错误的英文关键词,大概第一条就是解决问题的链接 Large number of "'function' is ...