//该工具类可以实现:给定一个指定的数据库表名,即可自动生成对应的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类转换工具的更多相关文章

  1. Java逆向工程(数据库表生成java类)

    说起来倒是挺简单的,就是听着名字感觉挺高大上.逆向工程方式有很多,比如mybatis就提供了一个这样的工具mybatis-genderator,这个我反正是没用过只是听说过,以前在公司都是用公司写好的 ...

  2. 我的Android进阶之旅------>Java文件大小转换工具类 (B,KB,MB,GB,TB,PB之间的大小转换)

    Java文件大小转换工具类 (B,KB,MB,GB,TB,PB之间的大小转换) 有时候要做出如下所示的展示文件大小的效果时候,需要对文件大小进行转换,然后再进行相关的代码逻辑编写. 下面是一个Java ...

  3. Oracle数据库中调用Java类开发存储过程、函数的方法

    Oracle数据库中调用Java类开发存储过程.函数的方法 时间:2014年12月24日  浏览:5538次 oracle数据库的开发非常灵活,不仅支持最基本的SQL,而且还提供了独有的PL/SQL, ...

  4. django根据已有数据库表生成model类

    django根据已有数据库表生成model类 创建一个Django项目 django-admin startproject 'xxxx' 修改setting文件,在setting里面设置你要连接的数据 ...

  5. EntityUtils MapStruct BeanCopier 数据实体类转换工具 DO BO VO DTO 附视频

    一.序言 在实际项目开发过程中,总有数据实体类互相转换的需求,DO.BO.VO.DTO等数据模型转换经常发生.今天推荐几个好用的实体类转换工具,分别是EntityUtils MapStruct Bea ...

  6. IDEA快速生成数据库表的实体类

    IDEA连接数据库 IDEA右边侧栏有个DataSource,可以通过这个来连接数据库,我们先成功连接数据库 点击进入后填写数据库进行连接,注意记得一定要去Test Connection 确保正常连接 ...

  7. 如何通过java反射将数据库表生成实体类?

    首先有几点声明: 1.代码是在别人的基础进行改写的: 2.大家有什么改进的意见可以告诉我,也可以自己改好共享给其他人: 3.刚刚毕业,水平有限,肯定有许多不足之处: 4.希望刚刚学习java的同学能有 ...

  8. java json转换工具类

    在java项目中,通常会用到json类型的转换,常常需要对 json字符串和对象进行相互转换. 在制作自定义的json转换类之前,先引入以下依赖 <!--json相关工具--><de ...

  9. sts使用mybatis插件直接生成数据库表的mapper类及配置文件

    首先点击help------>Eclipse Marketplace----->在find中搜索mybatis下面图片的第一个 点击installed 还需要一个配置文件generator ...

  10. mybatise插件反向生成数据库表相关Java代码

    1.下载相关jar包https://github.com/mybatis/generator/releases 2.配置xml文件 <?xml version="1.0" e ...

随机推荐

  1. Worktile团队协作平台介绍

    目前很多的基于SaaS模式的云平台都能满足你的需求,同类产品有很多,国内的明道.Worktile.http://Tower.im等,国外的Asana.Trello.Basecamp等,Trello是好 ...

  2. Mygin之错误恢复Recover中间件

    本篇是mygin这个系列的最后一篇.如果想自己动手实现一个类似Gin的Web框架,建议从 mgin第一篇开始, 总代码行数有效行数只有600多行 github源码 mygin 目的 实现错误处理机制 ...

  3. Cpu是如何选择线程的?

    Cpu是如何选择线程的? linux中线程存放格式 linux中线程与进程对应的结构体都是task_struct 唯一不同的点在于线程存放的东西少了点(由于一个进程中的线程们是共享一定数据的那些东西就 ...

  4. Matrix【未完成】

    Matrix The fitrst thing we do,let's kill all the language lawyers. -- Henry VI, Part II The "pr ...

  5. Hadoop的stop-all无法关闭集群原因及解决方案

    问题现象:在服务器上长时间运行hadoop之后,如果运行stop-all.sh,会发现: [root@node1 sbin]# stop-all.shThis script is Deprecated ...

  6. 二进制安装Kubernetes(k8s) v1.27.3 IPv4/IPv6双栈 可脱离互联网

    二进制安装Kubernetes(k8s) v1.27.3 IPv4/IPv6双栈 可脱离互联网 https://github.com/cby-chen/Kubernetes 开源不易,帮忙点个star ...

  7. Linux 中Yum命令使用方法

    Linux系统下常用yum安装命令详解   yum常用安装命令 使用yum安装和卸载软件,有个前提是yum安装的软件包都是rpm格式的. 1.安装killall命令yum install -y psm ...

  8. Frida 原理

    frida注入的主要思路: 1.找到目标进程,使用ptrace跟踪目标进程 2.获取mmap,dlpoen,dlsym等函数库的偏移 3.获取mmap,在目标进程申请一段内存空间,将在目标进程中找到存 ...

  9. libmatio开发笔记(一):matlab文件操作libmatio库介绍,编译和基础Demo

    前言   Qt可通过matlab的库对mat文件进行读写,第三方库matio也可以对mat文件进行读写,其已经支持mat文件的7.3版本.   libmatio库介绍   matio软件包含一个用于读 ...

  10. linux服务器界面初始--day01

    linux服务器界面初始 ip add show 查看服务器网卡信息还可以使用ifconfig 局域网ip: 192.168.1.0 10.0.0.0 172.16.1.0 如果网卡没有启用,我们需要 ...