工具类——通过数据库表自动生成java 实体类
程序员文章站
2022-06-15 13:42:52
...
maven
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
ColumnAttribute 类
public class ColumnAttribute {
//字段名称
private String columnName;
//字段类型
private String columType;
//字段长度
private int length;
//小数点后
private int scale;
//是否为 nullable
private int isNullable;
// 是否为主键
private boolean isPK;
// 属性
private String attributeName;
// 属性类型
private String attributeType;
// 字段说明
private String comment;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getColumType() {
return columType;
}
public void setColumType(String columType) {
this.columType = columType;
}
public int isNullable() {
return isNullable;
}
public void setNullable(int isNullable) {
this.isNullable = isNullable;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getScale() {
return scale;
}
public void setScale(int scale) {
this.scale = scale;
}
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getAttributeType() {
return attributeType;
}
public void setAttributeType(String attributeType) {
this.attributeType = attributeType;
}
public int getIsNullable() {
return isNullable;
}
public void setIsNullable(int isNullable) {
this.isNullable = isNullable;
}
public boolean isPK() {
return isPK;
}
public void setPK(boolean isPK) {
this.isPK = isPK;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
ColumnMapAttribute 类
public class ColumnMapAttribute {
/**
* @param s1 数据库里的表名
* @return 去掉下划线并且第一个字母开始大写
*/
public static String getBONameFormTable(String s1){
String tableName="";
String [] args=s1.split("_");
for(int i=0;i<args.length;i++){
String name=args[i];
if(name!=null && !"".equals(name)){
tableName=tableName+getStringFristUp(name);
}
}
return tableName;
}
/**
* @param s1 数据库里的字段
* @return 去掉下划线并且第二个字母开始大写
*/
public static String getAttibutreNameFormColumn(String s1){
String columnName="";
String [] args=s1.split("_");
for(int i=0;i<args.length;i++){
String name=args[i];
if(name!=null && !"".equals(name)){
if(i==0){
columnName=name.toLowerCase();
}else{
columnName=columnName+getStringFristUp(name);
}
}
}
return columnName;
}
/**
* 字符串首字母转大写,其他小写
* @param s
* @return
*/
private static String getStringFristUp(String s){
String result="";
if(s!=null && !"".equals(s)){
//
char[] chr=s.toCharArray();
for(int i=0;i<chr.length;i++) {
//如果ASCII码>96(小写字母)
if(i==0 && chr[i]>96){
chr[i]-=32;
}
//如果ASCII码<96(大写字母)
if(i>0 && chr[i]<96){
chr[i]+=32;
}
result=result+chr[i];
}
}
return result;
}
/**
* 字符串首字母转大写,其他不变
* @param s
* @return
*/
public static String getFristUp(String s){
String result="";
if(s!=null && !"".equals(s)){
//
char[] chr=s.toCharArray();
for(int i=0;i<chr.length;i++) {
//如果ASCII码>96(小写字母)
if(i==0 && chr[i]>96){
chr[i]-=32;
}
result=result+chr[i];
}
}
return result;
}
/**
*
* @param columnType oracle字段类型
* @param size 长度
* @param scan 小数点后面位数 主要判断number类型
* @return
*/
public static String getAttributeType(String columnType,int size,int scan){
String attributeType="";
// 可变字符
if("VARCHAR2".equalsIgnoreCase(columnType)){
attributeType="String";
}else if("CHAR".equalsIgnoreCase(columnType)){
attributeType="String";
}else if("NUMBER".equals(columnType)){
if(scan>0){
attributeType="double";
}else{
if(size<=8){
attributeType="int";
}else{
attributeType="int";
}
}
}else if("DATE".equals(columnType)){
attributeType="Date";
}else if("BIGINT".equalsIgnoreCase(columnType)){
attributeType="Long";
}else if("INTEGER".equalsIgnoreCase(columnType)){
attributeType="Integer";
}else if("TINYINT".equalsIgnoreCase(columnType)){
attributeType="Integer";
}else if("INT".equalsIgnoreCase(columnType)){
attributeType="Integer";
}else if("varchar".equalsIgnoreCase(columnType)){
attributeType="String";
}else if("timestamp".equalsIgnoreCase(columnType)){
attributeType="Date";
}else if("decimal".equalsIgnoreCase(columnType)){
attributeType="Double";
}else if("datetime".equalsIgnoreCase(columnType)){
attributeType="Date";
}else if("boolean".equalsIgnoreCase(columnType)){
attributeType="Boolean";
}else if("double".equalsIgnoreCase(columnType)){
attributeType="Double";
}
return attributeType;
}
public static void main(String args[]){
String s="DsFFDSFDFdsad";
String s2=getStringFristUp(s);
System.out.println(s2);
}
}
TableEntity 类
import java.util.List;
/**
* 表的映射实体
* @author Administrator
*
*/
public class TableEntity {
private String tableName;
private String boName;
private String primaryKeyName;
private String primaryIdName;
private List columnAttributes;
private List importClassList;
private String comment;
public TableEntity() {
super();
}
public String getBoName() {
return boName;
}
public void setBoName(String boName) {
this.boName = boName;
}
public List getColumnAttributes() {
return columnAttributes;
}
public void setColumnAttributes(List columnAttributes) {
this.columnAttributes = columnAttributes;
}
public List getImportClassList() {
return importClassList;
}
public void setImportClassList(List importClassList) {
this.importClassList = importClassList;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getPrimaryIdName() {
return primaryIdName;
}
public void setPrimaryIdName(String primaryIdName) {
this.primaryIdName = primaryIdName;
}
public String getPrimaryKeyName() {
return primaryKeyName;
}
public void setPrimaryKeyName(String primaryKeyName) {
this.primaryKeyName = primaryKeyName;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
TableToEntityMysql 类
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* mysql自动生成
*/
public class TableToEntityMysql{
/** 数据库连接URL*/
private final static String DB_URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
/** 数据库连接驱动*/
private final static String DB_DRIVER = "com.mysql.jdbc.Driver";
/** 数据库用户名*/
private final static String DB_USERNAME = "root";
/** 数据库密码*/
private final static String DB_PASSWORD = "123456";
/** 生成java实体类存放目录*/
private final static String FILEDIR = "D:\\beans_sharding_jdbc";
/**
* 生成bean前需修改的值
*/
/**数据库名称**/
public static String db_name="test";
/**要生成bean的表名**/
public static String table_name="user";
/**生成的bean类package值**/
public static String java_package_path="com.zhao.entity";
/**功能:主调方法
* @param args
* @author zhaoy
* @date 2017年11月2日
*/
public static void main(String[] args) {
/*
* 单个表生成bean
*/
// exportJava(table_name,java_package_path);
// /**
// * 批量表生成bean
// */
String[] tableArr={
"user",
// "tb_account_banks_card",
// "tb_account_extract"
};
exportBeansBatch(tableArr);
}
/**
* <p class="detail">
* 功能:数据库表批量生成bean
* </p>
* @author zhaoy
* @date 2017年11月2日
* @param tableNameArr 数据库表名字符串数组
*/
public static void exportBeansBatch(String tableNameArr[]){
for(int i=0; tableNameArr!=null && i<tableNameArr.length; i++){
try{
exportJava(tableNameArr[i],java_package_path);
}catch(Exception e){
System.out.println("第"+i+"个Bean生成失败,表名:"+tableNameArr[i]);
e.printStackTrace();
}
}
try {
Runtime.getRuntime().exec("explorer "+FILEDIR);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <p class="detail">
* 功能:根据表名称单个生成bean实体类
* </p>
* @author zhaoy
* @date 2017年11月2日
* @param tableName 数据库表名
* @param packageName 生成的bean类顶部包路径(package后面部分)
*/
public static void exportJava(String tableName,String packageName){
System.out.println(tableName+"表对应的bean正在生成...");
TableEntity entity=getTableEntity(tableName);
String boName=entity.getBoName();
List columnAttributes=entity.getColumnAttributes();
StringBuffer buffer = new StringBuffer();
String filePath=FILEDIR+"//"+boName+".java";
try {
if(packageName==null || "".equals(packageName)){
buffer.append("\n");
}else{
buffer.append("package "+packageName+";\n");
}
buffer.append("import javax.persistence.Column;\n");
buffer.append("import static javax.persistence.GenerationType.IDENTITY;\n");
buffer.append("import javax.persistence.Entity;\n");
buffer.append("import javax.persistence.GeneratedValue;\n");
buffer.append("import javax.persistence.Id;\n");
buffer.append("import javax.persistence.Table;\n");
buffer.append("import java.util.Date;\n");
buffer.append("\[email protected]\n");
buffer.append("@Table(name =\" "+tableName+"\")\n");
buffer.append(" public class "+boName+" implements java.io.Serializable{\n");
writeBOMessage(buffer,entity);
writeSetGet(buffer,columnAttributes);
buffer.append("}\n");
File beanDir=new File(FILEDIR);
if(!beanDir.isDirectory()){
beanDir.mkdir();
}
File beanFile=new File(filePath);
if(!beanFile.exists()){
beanFile.createNewFile();
}
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(filePath),"UTF-8");
out.write(buffer.toString());
out.flush();
out.close();
System.out.println(tableName+"表对应的bean生成成功:"+filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 功能:获取数据库所有表名
* @param tableName
* @return
* @author zhaoy
* @date 2017年11月2日
*/
public static TableEntity getTableEntity(String tableName){
TableEntity entity=new TableEntity();
List columnAttributes=new ArrayList();
//当前用户有权限查看的所有表的表名
PreparedStatement pstm=null;
Connection con=null;
ResultSetMetaData rsm=null;
String sql="SELECT * FROM "+tableName+" limit 0,1";
try {
con=getConnection();
DatabaseMetaData dbMeta = con.getMetaData();
ResultSet pkRSet=dbMeta.getPrimaryKeys(null,null,tableName);
String primaryKey="";
while(pkRSet.next()){
primaryKey=pkRSet.getString(4);
break;
}
entity.setPrimaryKeyName(primaryKey);
entity.setPrimaryIdName(ColumnMapAttribute.getAttibutreNameFormColumn(primaryKey));
pstm = con.prepareStatement(sql);
pstm.executeQuery();
rsm=pstm.getMetaData();
for(int i=1;i<=rsm.getColumnCount();i++){
ColumnAttribute columnAttribute=new ColumnAttribute();
// 字段名
String columnName=rsm.getColumnName(i);
columnAttribute.setColumnName(columnName);
if(columnName.equals(primaryKey)){
columnAttribute.setPK(true);
}else{
columnAttribute.setPK(false);
}
// 字段类型
String columnType=rsm.getColumnTypeName(i);
if("CLOB".equals(columnType)){
continue;
}
columnAttribute.setColumType(columnType);
// 字段长度
int columnSize=rsm.getPrecision(i);
columnAttribute.setLength(columnSize);
// 获取指定列的小数点右边的位数。
int scale=rsm.getScale(i);
//System.out.println("字段名称: "+rsm.getColumnLabel(i)+"\n\t sql类型编号:"+rsm.getColumnType(i)+"\n\t sql类型名称:"+rsm.getColumnTypeName(i)+"\n\t scale:"+rsm.getScale(i)+"\n\t sql类型精确度:"+rsm.getPrecision(i)+"\n\t 最大字符个数:"+rsm.getColumnDisplaySize(i)+"\n\t java类型:"+rsm.getColumnClassName(i));
columnAttribute.setScale(scale);
// 是否必填
int isNullable=rsm.isNullable(i);
columnAttribute.setNullable(isNullable);
columnAttribute.setAttributeName(ColumnMapAttribute.getAttibutreNameFormColumn(columnName));
columnAttribute.setAttributeType(ColumnMapAttribute.getAttributeType(columnType,columnSize,scale));
// 字段描述
String coments=getColumnComments(con,tableName,columnName);
columnAttribute.setComment(coments);
columnAttributes.add(columnAttribute);
}
entity.setBoName(ColumnMapAttribute.getBONameFormTable(tableName));
entity.setColumnAttributes(columnAttributes);
} catch (SQLException e) {
e.printStackTrace();
} finally{
//closeConn(pstm,null,con);
}
return entity;
}
/**
* 功能:获得字段说明
* @param con
* @param tableName
* @param columnName
* @return
* @throws SQLException
* @author zhaoy
* @throws Exception
* @date 2017年11月2日
*/
private static String getColumnComments(Connection con, String tableName, String columnName) throws SQLException {
//String sql=" select t.TABLE_NAME,t.COLUMN_NAME,t.comments from user_col_comments t where t.table_name=? and t.column_name=? ";
String sql="SELECT t.`TABLE_NAME`,t.`COLUMN_NAME`,t.`COLUMN_COMMENT` FROM information_schema.columns t WHERE t.`TABLE_SCHEMA`='"+db_name+"' AND t.table_name='"+tableName+"' and t.`COLUMN_NAME`='"+columnName+"' ORDER BY t.table_schema,t.table_name";
PreparedStatement pstm=con.prepareStatement(sql);
ResultSet rt = pstm.executeQuery();
String colDesc="";
if(rt.next()){
colDesc=rt.getString(3);
}
return colDesc;
}
/**
* 功能:创建文件夹并返回写入此文件的FileWriter对象
* @param name
* @return
* @author zhaoy
* @date 2017年11月2日
*/
private static FileWriter createFile(String name){
File dir=new File(FILEDIR);
if(!dir.exists()){
dir.mkdirs();
}
String fileName=FILEDIR+"//"+name+".java";
System.out.println(fileName);
File file=new File(fileName);
FileWriter writer=null;
try {
if(!file.exists()){
file.createNewFile();
}
writer=new FileWriter(file);
} catch (IOException e) {
e.printStackTrace();
}
return writer;
}
/**
* 功能:写入字段定义及构造函数-默认无参数,全部参数2个
* @param writer
* @param entity
* @throws IOException
* @author zhaoy
* @date 2017年11月2日
*/
private static void writeBOMessage(StringBuffer writer,TableEntity entity) throws IOException{
String boName=entity.getBoName();
String paimaryIdName=entity.getPrimaryIdName();
String parimaryIdType="";
List columnAttributes=entity.getColumnAttributes();
// 所有成员变量的定义
for(int i=0;columnAttributes!=null && i<columnAttributes.size();i++){
writer.append("\n");
ColumnAttribute columnAttribute=(ColumnAttribute)columnAttributes.get(i);
if(paimaryIdName!=null && paimaryIdName.equals(columnAttribute.getAttributeName())){
parimaryIdType=columnAttribute.getAttributeType();
}
writer.append(" /** "+columnAttribute.getComment()+" */\n");
writer.append(" private "+columnAttribute.getAttributeType()+" "+columnAttribute.getAttributeName()+";\n");
}
writer.append("\n");
// 无参构造方法
writer.append(" public "+boName+" (){\n");
writer.append(" super(); \n }\n");
// 全部参数构造方法
// 主键构造方法
if(paimaryIdName!=null && !paimaryIdName.equals("")){
writer.append(" public "+boName+"("+parimaryIdType+" "+paimaryIdName+"){\n");
writer.append(" this."+paimaryIdName+"="+paimaryIdName+";\n");
writer.append(" }\n");
}
}
/**
* 功能:bo类set和get方法的生成,包括各个属性
* @param writer
* @param columnAttributes
* @throws IOException
* @author zhaoy
* @date 2017年11月2日
*/
private static void writeSetGet(StringBuffer writer,List columnAttributes) throws IOException{
for(int i=0;i<columnAttributes.size();i++){
writer.append("\n");
ColumnAttribute columnAttribute=(ColumnAttribute)columnAttributes.get(i);
String attributeName=columnAttribute.getAttributeName();
String attributeNameUP=ColumnMapAttribute.getFristUp(attributeName);
String attributeType=columnAttribute.getAttributeType();
//set方法
if(((ColumnAttribute)columnAttributes.get(i)).isPK()){
writer.append("\t @Id\n");
writer.append("\t @GeneratedValue(strategy = IDENTITY)\n");
writer.append("\t @Column(name = \"id\", unique = true, nullable = false)\n");
}else{
writer.append("\t @Column(name =\""+((ColumnAttribute)columnAttributes.get(i)).getColumnName()+"\")\n");
}
writer.append(" public "+attributeType+" get"+attributeNameUP+"(){\n");
writer.append(" return this."+attributeName+";\n");
writer.append(" }");
writer.append("\n");
//get方法
writer.append(" public void set"+attributeNameUP+"("+attributeType+" "+attributeName+"){\n");
writer.append(" this."+attributeName+"="+attributeName+";\n");
writer.append(" }");
writer.append("\n");
}
}
/**
* 功能:关闭数据库链接
* @param stmt
* @param rt
* @param dbConn
* @author zhaoy
* @date 2017年11月2日
*/
public static void closeConn(Statement stmt,ResultSet rt,Connection dbConn){
try {
if(stmt!=null && stmt.isClosed()){
stmt.close();
}
if(rt!=null && rt.isClosed()){
rt.close();
}
if(dbConn!=null && dbConn.isClosed()){
dbConn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 功能:获得数据库链接
* @return
* @author zhaoy
* @date 2017年11月2日
*/
public static Connection getConnection(){
Connection conn = null;
try{
//注册驱动
Class.forName(DB_DRIVER);
conn = DriverManager.getConnection(DB_URL,DB_USERNAME,DB_PASSWORD);
}catch(Exception ex){
ex.printStackTrace();
}
return conn;
}
}
上一篇: MySQL大批量删除数据
推荐阅读
-
通过T4模板生成数据库实体类,妈妈再也不用担心我用CodeFirst了!!!
-
使用IDEA插件EasyCode实现数据库表反向生成实体类
-
写一个工具生成数据库实体类
-
C#实现根据实体类自动创建数据库表
-
Mybatis通过数据库表自动生成实体类和xml映射文件
-
java代码自动生成数据库表中对应的类文件及操作数据库功能
-
mybatis plus generator 根据数据库自动生成实体类的实现示例
-
mybatis-plus 使用Generator 工具类自动生成dao 实体类 service mapper类
-
根据数据库表名和主键自动生成 springbootJpa的 Dao层和Service层工具类
-
如何用nodejs给C#写一个数据表的实体类生成工具