利用Java将Mysql数据表生成JPA实体对象_MySQL

WBOY
发布: 2016-06-01 13:06:53
原创
1172 人浏览过

package cn.lry.xp;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DatabaseMetaData;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

/**

* 从数据库表反射出实体类,自动生成实体类

* @author lry

*

*/

public class GenEntityMysql {

private String packageOutPath = "cn.lry.po";//指定实体生成所在包的路径

private String authorName = "lry";//作者名字

private String tablename = "";//表名

private String[] colnames; // 列名数组

private String[] colTypes; //列名类型数组

private int[] colSizes; //列名大小数组

private boolean f_util = false; // 是否需要导入包java.util.*

private boolean f_sql = false; // 是否需要导入包java.sql.*

private boolean f_jpa = true; // 是否需要生成基于注解的JPA实体对象

//数据库连接

private static final String URL ="jdbc:mysql://localhost:3306/mytest";

private static final String NAME = "root";

private static final String PASS = "123456";

private static final String DRIVER ="com.mysql.jdbc.Driver";

/*

* 构造函数

*/

public GenEntityMysql(){

List list=getTableName();

for(int p=0;p

tablename=list.get(p);

//创建连接

Connection con;

//查要生成实体类的表

String sql = "select * from " + tablename;

PreparedStatement pStemt = null;

try {

try {

Class.forName(DRIVER);

} catch (ClassNotFoundException e1) {

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

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")){

f_sql = true;

}

colSizes[i] = rsmd.getColumnDisplaySize(i + 1);

}

String content = parse(colnames,colTypes,colSizes);

try {

File directory = new File("");

String outputPath = directory.getAbsolutePath()+ "/src/"+this.packageOutPath.replace(".", "/")+"/"+initcap(tablename) + ".java";

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{

//try {

//con.close();

/

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板