如何讓java只根據(jù)數(shù)據(jù)庫表名自動生成實體類
根據(jù)數(shù)據(jù)庫表名生成實體類
公司用的jpa,沒有用mybatis。所以也沒有用mybatis自動生成。但有些數(shù)據(jù)庫表字段太多,就想著一勞永逸了,連數(shù)據(jù)庫注釋都搞上去
第一種
這里使用的是jdbcTemplate+Junit測試生成,方式可變。
SpringBoot版本是2.4.4,只需要加上@SpringBootTest就可以了。不用@RunWith
pom:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency>
代碼
package com.shinedata.bims.web; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName TestController * @Author yupanpan * @Date 2021/4/12 14:24 */ @SpringBootTest public class TestController { @Autowired private JdbcTemplate jdbcTemplate; @Test public void database(){ createEntity("1ceping", "t_evaluation_template_info_copy","com.shinedata.bims.entity",false); } /** * * @param dataBaseName 數(shù)據(jù)庫名 * @param tableName 表名 * @param packageName 包名 * @param isAddEntitySuffix 類名是否添加Entity后綴 true-添加 false-不添加 */ public void createEntity(String dataBaseName,String tableName,String packageName,boolean isAddEntitySuffix){ String className=tableName; if(tableName.substring(0,2).equals("t_")){ StringBuilder stringBuilder = new StringBuilder(tableName); stringBuilder.replace(0, 2, ""); String initialsUpperCase = stringBuilder.substring(0, 1).toUpperCase(); className=initialsUpperCase+stringBuilder.substring(1); } className=removeUnderline(className)+(isAddEntitySuffix?"Entity":""); StringBuffer classBuffer=new StringBuffer(); classBuffer.append("import java.util.Date;\r\n"); classBuffer.append("import java.time.LocalDateTime;\r\n"); classBuffer.append("import com.alibaba.fastjson.JSONObject;\r\n"); classBuffer.append("import java.lang.*;\r\n"); classBuffer.append("import java.math.*;\r\n"); classBuffer.append("import java.sql.*;\r\n"); classBuffer.append("import lombok.Data;\r\n\r\n\r\n"); classBuffer.append("@Data\r\n"); classBuffer.append("public class " + className + " {\r\n\r\n"); List<Map> filedMaps = getFiledMaps(dataBaseName, tableName); processAllAttrs(classBuffer,filedMaps); classBuffer.append("}\r\n"); markerBean(className,classBuffer.toString(),packageName); } /** * 創(chuàng)建實體類文件 * @param className 類名(不包含.java文件名后綴) 根據(jù)表名首字母大寫并去掉開頭t_和所有下劃線-駝峰命名 * @param content 添加的內(nèi)容(字段注釋等) * @param packageName 包名(com.xxx.xxx.xxx) */ public void markerBean(String className, String content, String packageName) { String folder = System.getProperty("user.dir") + "/src/main/java/" + packageName.replace(".","/") + "/"; File file = new File(folder); if (!file.exists()) { file.mkdirs(); } String fileName = folder + className + ".java"; try { File newjava = new File(fileName); FileWriter fw = new FileWriter(newjava); fw.write("package\t" + packageName + ";\r\n"); fw.write(content); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 解析輸出屬性 * * @return */ private void processAllAttrs(StringBuffer sb,List<Map> filedMaps) { for (int i = 0; i < filedMaps.size(); i++) { Map map = filedMaps.get(i); String fieldType = MapUtils.getString(map, "fieldType"); String fieldName = MapUtils.getString(map, "fieldName"); String fieldComment = MapUtils.getString(map, "fieldComment"); if(StringUtils.isNotBlank(fieldComment)){ sb.append("\t/**\r\n").append("\t* ").append(fieldComment).append("\n").append("\t*/\r\n"); } sb.append("\tprivate " + fieldType + " " + fieldName + ";\r\n\r\n"); } } /** * 獲取表字段信息(列名、類型、注釋等) * @param dataBaseName * @param tableName * @return */ private List<Map> getFiledMaps(String dataBaseName,String tableName) { String sql="SELECT * FROM information_schema.`COLUMNS` WHERE TABLE_SCHEMA ='"+dataBaseName+"' AND TABLE_NAME = '"+tableName+"'"; List<Map> tableFieldList = jdbcTemplate.query(sql, new RowMapper<Map>() { @Override public Map<String,String> mapRow(ResultSet resultSet, int rowNum) throws SQLException { Map<String,String> fieldMap = new HashMap(); String column_name = resultSet.getString("COLUMN_NAME"); setFieldName(column_name.toLowerCase(),fieldMap); String data_type = resultSet.getString("DATA_TYPE"); setFieldType(data_type.toUpperCase(),fieldMap); fieldMap.put("fieldComment",resultSet.getString("COLUMN_COMMENT")); return fieldMap; } }); return tableFieldList; } private void setFieldName(String columnName, Map fieldMap) { fieldMap.put("fieldName",removeUnderline(columnName)); } /** * 去下劃線 * @param string * @return */ public String removeUnderline(String string){ StringBuilder columnNameBuilder=new StringBuilder(string); if(!string.contains("_")){ return string; }else { int i = columnNameBuilder.indexOf("_"); columnNameBuilder.replace(i,i+1, "").replace(i,i+1,columnNameBuilder.substring(i,i+1).toUpperCase()); return removeUnderline(columnNameBuilder.toString()); } } private void setFieldType(String columnType,Map fieldMap){ String fieldType="String"; if(columnType.equals("INT")||columnType.equals("INTEGER")){ fieldType="Integer"; }else if(columnType.equals("BIGINT")){ fieldType="Long"; }else if(columnType.equals("DATETIME")){ fieldType="Date"; }else if(columnType.equals("TEXT")||columnType.equals("VARCHAR")||columnType.equals("TINYTEXT")||columnType.equals("LONGTEXT")){ fieldType="String"; }else if(columnType.equals("DOUBLE")){ fieldType="Double"; }else if(columnType.equals("BIT")){ fieldType="Boolean"; }else if(columnType.equals("FLOAT")){ fieldType="Float"; }else if(columnType.equals("DECIMAL")){ fieldType="BigDecimal"; }else if(columnType.equals("DATE")){ fieldType="Date"; }else if(columnType.equals("TIMESTAMP")){ fieldType="LocalDateTime"; }else if(columnType.equals("CHAR")){ fieldType="Char"; }else if(columnType.equals("JSON")){//mysql5.7版本才開始有的 fieldType="JSONObject"; } fieldMap.put("fieldType",fieldType); } }
生成的類
用的lombok,就懶得去搞getset了
第二種
搞的是直接main方法運行下就生成,大同小異。不用Junit,方便一些,就是個工具。和第一種結(jié)果一樣的
package com.shinedata.bims.web; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.*; import java.util.*; /** * @ClassName TableToEntityUtils * @Author yupanpan * @Date 2021/6/8 17:25 */ public class TableToEntityUtils { static final String USER = "root"; static final String PASS = "xxxxxxxxxxx"; // static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; // MySQL 8.0 以下版本 - JDBC 驅(qū)動名及數(shù)據(jù)庫 URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://xxxxxxxxxxxxxxxxxxxxxxx:3306/1ceping?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&allowMultiQueries=true&rewriteBatchedStatements=true"; public static void main(String[] args) throws Exception { createEntity("1ceping", "t_evaluation_template_info_copy","com.shinedata.bims.entity",false); } /** * * @param dataBaseName 數(shù)據(jù)庫名 * @param tableName 表名 * @param packageName 包名 * @param isAddEntitySuffix 類名是否添加Entity后綴 true-添加 false-不添加 */ public static void createEntity(String dataBaseName, String tableName, String packageName, boolean isAddEntitySuffix) throws Exception{ String className=tableName; if(tableName.substring(0,2).equals("t_")){ StringBuilder stringBuilder = new StringBuilder(tableName); stringBuilder.replace(0, 2, ""); String initialsUpperCase = stringBuilder.substring(0, 1).toUpperCase(); className=initialsUpperCase+stringBuilder.substring(1); } className=removeUnderline(className)+(isAddEntitySuffix?"Entity":""); StringBuffer classBuffer=new StringBuffer(); classBuffer.append("import java.util.Date;\r\n"); classBuffer.append("import java.time.LocalDateTime;\r\n"); classBuffer.append("import com.alibaba.fastjson.JSONObject;\r\n"); classBuffer.append("import java.lang.*;\r\n"); classBuffer.append("import java.math.*;\r\n"); classBuffer.append("import java.sql.*;\r\n"); classBuffer.append("import lombok.Data;\r\n\r\n\r\n"); classBuffer.append("@Data\r\n"); classBuffer.append("public class " + className + " {\r\n\r\n"); List<Map> filedMaps = getFiledMaps(dataBaseName, tableName); processAllAttrs(classBuffer,filedMaps); classBuffer.append("}\r\n"); markerBean(className,classBuffer.toString(),packageName); } /** * 創(chuàng)建實體類文件 * @param className 類名(不包含.java文件名后綴) 根據(jù)表名首字母大寫并去掉開頭t_和所有下劃線-駝峰命名 * @param content 添加的內(nèi)容(字段注釋等) * @param packageName 包名(com.xxx.xxx.xxx) */ public static void markerBean(String className, String content, String packageName) throws Exception { // 這里不使用System.getProperty("user.dir")了。user.dir是根據(jù)運行時環(huán)境來的 File f2 = new File(TableToEntityUtils.class.getResource("/").getPath()); String homePath=f2.getCanonicalPath().replace("\\target\\classes", ""); String folder = homePath + "/src/main/java/" + packageName.replace(".","/") + "/"; File file = new File(folder); if (!file.exists()) { file.mkdirs(); } String fileName = folder + className + ".java"; try { File newjava = new File(fileName); FileWriter fw = new FileWriter(newjava); fw.write("package\t" + packageName + ";\r\n"); fw.write(content); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 去下劃線 * @param string * @return */ public static String removeUnderline(String string){ StringBuilder columnNameBuilder=new StringBuilder(string); if(!string.contains("_")){ return string; }else { int i = columnNameBuilder.indexOf("_"); columnNameBuilder.replace(i,i+1, "").replace(i,i+1,columnNameBuilder.substring(i,i+1).toUpperCase()); return removeUnderline(columnNameBuilder.toString()); } } /** * 獲取表字段信息(列名、類型、注釋等) * @param dataBaseName * @param tableName * @return */ private static List<Map> getFiledMaps(String dataBaseName, String tableName) { Connection conn = null; Statement stmt = null; List<Map> tableFieldList=new ArrayList<>(); try{ // 注冊 JDBC 驅(qū)動 Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 執(zhí)行查詢 stmt = conn.createStatement(); String sql= "SELECT * FROM information_schema.`COLUMNS` WHERE TABLE_SCHEMA ='"+dataBaseName+"' AND TABLE_NAME= '"+tableName+"'"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { Map<String,String> fieldMap = new HashMap(); String column_name = rs.getString("COLUMN_NAME"); setFieldName(column_name.toLowerCase(),fieldMap); String data_type = rs.getString("DATA_TYPE"); setFieldType(data_type.toUpperCase(),fieldMap); fieldMap.put("fieldComment",rs.getString("COLUMN_COMMENT")); tableFieldList.add(fieldMap); } rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // 處理 JDBC 錯誤 se.printStackTrace(); }catch(Exception e){ // 處理 Class.forName 錯誤 e.printStackTrace(); }finally{ // 關(guān)閉資源 try{ if(stmt!=null){ stmt.close(); } }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } return tableFieldList; } /** * 解析輸出屬性 * * @return */ private static void processAllAttrs(StringBuffer sb, List<Map> filedMaps) { for (int i = 0; i < filedMaps.size(); i++) { Map map = filedMaps.get(i); String fieldType = MapUtils.getString(map, "fieldType"); String fieldName = MapUtils.getString(map, "fieldName"); String fieldComment = MapUtils.getString(map, "fieldComment"); if(StringUtils.isNotBlank(fieldComment)){ sb.append("\t/**\r\n").append("\t* ").append(fieldComment).append("\n").append("\t*/\r\n"); } sb.append("\tprivate " + fieldType + " " + fieldName + ";\r\n\r\n"); } } private static void setFieldName(String columnName, Map fieldMap) { fieldMap.put("fieldName",removeUnderline(columnName)); } private static void setFieldType(String columnType, Map fieldMap){ String fieldType="String"; if(columnType.equals("INT")||columnType.equals("INTEGER")){ fieldType="Integer"; }else if(columnType.equals("BIGINT")){ fieldType="Long"; }else if(columnType.equals("DATETIME")){ fieldType="Date"; }else if(columnType.equals("TEXT")||columnType.equals("VARCHAR")||columnType.equals("TINYTEXT")||columnType.equals("LONGTEXT")){ fieldType="String"; }else if(columnType.equals("DOUBLE")){ fieldType="Double"; }else if(columnType.equals("BIT")){ fieldType="Boolean"; }else if(columnType.equals("FLOAT")){ fieldType="Float"; }else if(columnType.equals("DECIMAL")){ fieldType="BigDecimal"; }else if(columnType.equals("DATE")){ fieldType="Date"; }else if(columnType.equals("TIMESTAMP")){ fieldType="LocalDateTime"; }else if(columnType.equals("CHAR")){ fieldType="Char"; }else if(columnType.equals("JSON")){//mysql5.7版本才開始有的 fieldType="JSONObject"; } fieldMap.put("fieldType",fieldType); } }
到此這篇關(guān)于如何讓java只根據(jù)數(shù)據(jù)庫表名自動生成實體類的文章就介紹到這了,更多相關(guān)根據(jù)數(shù)據(jù)庫表名生成實體類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Jenkins自動化部署SpringBoot項目的實現(xiàn)
本文主要介紹了Jenkins自動化部署SpringBoot項目的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2023-01-01Mybatis動態(tài)調(diào)用表名和字段名的解決方法
今天在項目開發(fā)中有個業(yè)務(wù)是需要限制各個用戶對某些表里的字段查詢以及某些字段是否顯示,這種情況下,就需要構(gòu)建sql來動態(tài)傳入表名、字段名了,下面給大家介紹mybatis動態(tài)調(diào)用表名和字段名的解決方法,一起看看吧2016-10-10Java日期操作方法工具類實例【包含日期比較大小,相加減,判斷,驗證,獲取年份等】
這篇文章主要介紹了Java日期操作方法工具類,結(jié)合完整實例形式分析了java針對日期的各種常見操作,包括日期比較大小,相加減,判斷,驗證,獲取年份、天數(shù)、星期等,需要的朋友可以參考下2017-11-11基于Freemarker和xml實現(xiàn)Java導(dǎo)出word
這篇文章主要介紹了基于Freemarker和xml實現(xiàn)Java導(dǎo)出word,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04Mybatis-plus:${ew.sqlselect}用法說明
這篇文章主要介紹了Mybatis-plus:${ew.sqlselect}用法說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06最新IntelliJ?IDEA?2022配置?Tomcat?8.5?的詳細步驟演示
這篇文章主要介紹了IntelliJ?IDEA?2022?詳細配置?Tomcat?8.5?步驟演示,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08