//该工具类可以实现:给定一个指定的数据库表名,即可自动生成对应的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. 10、数据库学习规划:MySQL - 学习规划系列文章

    MySQL数据库是笔者认识的几个流行的数据库之一.类似于Linux重装系统,其也是开源的,最主要是有很多的社区支持,众多的开发者对其能够进行使用,所以其功能也挺强大,便于使用.通过对MySQL数据库的 ...

  2. 盘点Java集合(容器)概览,Collection和Map在开发中谁用的最多?

    写在开头 在Java的世界里万物皆对象.但我认为是万物皆数据,世界由各种各样数据构建起来,我们通过程序去实现数据的增删改查.转入转出.加减乘除等等,不同语言的实现方式殊途同归.由此可见,数据对于程序语 ...

  3. 【译】使用.NET将WebAssembly扩展到云(一)

    原文 | Richard Lander 翻译 | 郑子铭 WebAssembly(Wasm)是一种令人兴奋的新虚拟机和(汇编)指令格式. Wasm 诞生于浏览器,是 Blazor 项目的重要组成部分. ...

  4. mysql插入表中的中文字符显示为乱码或问号的解决方法

    mysql中文显示乱码或者问号是因为选用的编码不对或者编码不一致造成的,最简单的方法就是修改mysql的配置文件my.cnf.在[mydqld]和[client]段加入 default-charact ...

  5. 3分钟总览微软TPL并行编程库

    有小伙伴问我每天忽悠的TPL是什么?☹️ 这次站位高一点,严肃讲一讲. 引言 俗话说,不想开飞机的程序员不是一名好爸爸:作为微软技术栈的老鸟,一直将代码整洁之道奉为经典, 优秀的程序员将优雅.高性能的 ...

  6. 我的小程序之旅二:如何创建一个微信小程序

    第一步.准备邮箱 如果只是个人想体验一下小程序,直接用自己的QQ邮箱就行,但是这样申请的小程序很多权限都是没有的,比如获取用户手机号授权. 如果是企业或服务商要进行开发小程序,那么至少准备三个邮箱,同 ...

  7. 编译 windows 上的 qt 静态库

    记录命令行编译过程: 针对 Qt 5.15.2 版本, 只需要 Source 文件就行 打开 x86 Native Tools Command Prompt for VS 2019,如果需要编译 x6 ...

  8. 【Android逆向】脱壳项目 frida-dexdump 原理分析

    1. 项目代码地址 https://github.com/hluwa/frida-dexdump 2. 核心逻辑为 def dump(self): logger.info("[+] Sear ...

  9. RK3568开发笔记(三):RK3568虚拟机基础环境搭建之更新源、安装网络工具、串口调试、网络连接、文件传输、安装vscode和samba共享服务

    前言   开始搭建RK3568的基础虚拟机,具备基本的通用功能,主要包含了串口工具minicom,远程登陆ssh,远程传输filezilla,代码编辑工具vscode.   虚拟机   文档对对虚拟机 ...

  10. React 组件懒加载

    只有不断学习和成长,才能适应这个快速变化的世界. 1. 懒加载 1.1 React 懒加载 React 中懒加载 Lazy 与 Suspense 需要搭配使用. React.lazy 定义: Reac ...