Springboot 自動生成實體程式碼 屬性帶註釋(未優化) 詳細步驟(一)
阿新 • • 發佈:2018-11-19
框架:springboot+codemodel 自動生成實體程式碼
①引入codemodel的jar
<!-- https://mvnrepository.com/artifact/com.sun.codemodel/codemodel-project --> <dependency> <groupId>com.sun.codemodel</groupId> <artifactId>codemodel</artifactId> <version>2.6</version> </dependency>
②在application.properties中配置資料來源
③編寫連線DB工具類
package cn.allsales.tools; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import cn.allsales.pojo.DataBaseConfig; /** * 連線DB工具 * @author 橘貓 * */ @Component public class DBUtil { protected final Logger log= (Logger) LoggerFactory.getLogger(DBUtil.class); //獲取配置 @Autowired private DataBaseConfig config; public Connection conn = null; public String url=null; /** * 獲得連線 * @return */ public Connection getConnection() { try { // 註冊驅動,為了相容JVM所以才加上newInstance() Class.forName(config.getDriver()).newInstance(); try { url=config.getUrl(); //管理連線 conn = DriverManager.getConnection(url, config.getUsername(), config.getPassword()); } catch (SQLException e) { log.error("connection:{}","An exception connecting to the database"); e.printStackTrace(); } } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { log.error("class.forName:{}","DRIVER ERROR,please check application.properites "); e.printStackTrace(); } return conn; } /** * 關閉資料庫連線 */ public void closeConnection() { if(null!=conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); log.error("close connect:{}","Close data exception"); } } } }
④編寫獲取資料表資訊介面
package cn.allsales.tools; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedHashSet; import org.springframework.stereotype.Component; import cn.allsales.pojo.TableInfoPOJO; @Component public class TableInfo extends DBUtil{ /** * 通過表名獲取到表的資訊 * @param tableName */ public LinkedHashSet<TableInfoPOJO>getTableInfo(String tableName) { //獲取連線 Connection conn = getConnection(); ResultSet rs=null; LinkedHashSet<TableInfoPOJO> set=new LinkedHashSet<>(); try { //獲取到表的元資料 DatabaseMetaData meta=conn.getMetaData(); //conn.getCatalog獲取到資料庫名字 rs = meta.getColumns(conn.getCatalog(), null, tableName, null); while(rs.next()) { TableInfoPOJO pojo=new TableInfoPOJO(); pojo.setColumnName(rs.getString("COLUMN_NAME")); pojo.setRemarks(rs.getString("REMARKS")); pojo.setTypeName(rs.getString("TYPE_NAME")); set.add(pojo); } return set; } catch (SQLException e) { log.error("DataBaseMetaData:{}","Error retrieving metadata"); e.printStackTrace(); }finally { if(null !=rs) { try { rs.close(); } catch (SQLException e) { log.error("close ResultSet:{}","Close the abnormal"); e.printStackTrace(); } } //關閉連線 closeConnection(); } return null; } }
⑤編寫自動生成實體程式碼
package cn.allsales.tools;
import java.io.File;
import java.util.LinkedHashSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JFieldRef;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JType;
import cn.allsales.pojo.TableInfoPOJO;
import cn.allsales.tools.TableInfo;
/**
* 生成實體
* @author admin
*
*/
@Component
public class GenerateEntity {
@Autowired
private TableInfo info;
/**
* 生成實體
* @param tableName 表名
* @param aliasName 別名
* @throws Exception
*/
@SuppressWarnings("unused")
public void getGenerate(String tableName,String aliasName) throws Exception{
//建立model
JCodeModel cm = new JCodeModel();
//設定類名
JType cn=null;
if(null==aliasName) {
cn = cm.parseType(tableName);
}else {
cn=cm.parseType(aliasName);
}
//設定存放路徑
File file=new File("src/main/java");
//設定存放包
JDefinedClass dc = cm._class("cn.allsales.entity."+aliasName);
//根據表名獲得類成員
LinkedHashSet<TableInfoPOJO> tableInfo = info.getTableInfo(tableName);
//定義建構函式
dc.constructor(JMod.PRIVATE);
for (TableInfoPOJO pojo : tableInfo) {
String type = this.getAbilityType(pojo.getTypeName()).trim();
//定義成員
JFieldVar field = dc.field(JMod.PRIVATE, cm.parseType(type), pojo.getColumnName());
//生成javadoc
field.javadoc().add(pojo.getRemarks());
//列名首字母大寫
String name=pojo.getColumnName().substring(0,1).toUpperCase()+pojo.getColumnName().substring(1);
//定義成員的get方法
JMethod method = dc.method(JMod.PUBLIC, cm.parseType(type),"get"+name);
//建立get身體
JBlock getInstanceBody = method.body();
JFieldRef fieldRef = JExpr.ref(pojo.getColumnName());
/*//新增if判斷
JConditional conditionIf = getInstanceBody._if(fieldRef.eq(JExpr
._null()));
JBlock thenPart = conditionIf._then();
thenPart.assign(fieldRef, JExpr._new(cm.parseType(type),)); */
getInstanceBody._return(fieldRef);
//定義成員set方法
JMethod methodSet = dc.method(JMod.PUBLIC, cm.parseType("void"), "set"+name);
//建立set身體
JBlock body = methodSet.body();
//設定set方法引數
methodSet.param(cm.parseType(type), pojo.getColumnName());
JFieldRef ihs = JExpr.ref(pojo.getColumnName());
body.assign(JExpr.refthis(pojo.getColumnName()), ihs);
}
cm.build(file);
}
/**
* 表名
* @param tableName
* @throws Exception
*/
@SuppressWarnings("unused")
public void getGenerate(String tableName) throws Exception{
//建立model
JCodeModel cm = new JCodeModel();
//設定類名
JType cn = cm.parseType(tableName);
//設定存放路徑
File file=new File("src/main/java");
//設定存放包
JDefinedClass dc = cm._class("cn.allsales.entity."+tableName);
//根據表名獲得類成員
LinkedHashSet<TableInfoPOJO> tableInfo = info.getTableInfo(tableName);
//定義建構函式
dc.constructor(JMod.PRIVATE);
for (TableInfoPOJO pojo : tableInfo) {
String type = this.getAbilityType(pojo.getTypeName()).trim();
//定義成員
JFieldVar field = dc.field(JMod.PRIVATE, cm.parseType(type), pojo.getColumnName());
//生成javadoc
field.javadoc().add(pojo.getRemarks());
//列名首字母大寫
String name=pojo.getColumnName().substring(0,1).toUpperCase()+pojo.getColumnName().substring(1);
//定義成員的get方法
JMethod method = dc.method(JMod.PUBLIC, cm.parseType(type),"get"+name);
//建立get身體
JBlock getInstanceBody = method.body();
JFieldRef fieldRef = JExpr.ref(pojo.getColumnName());
/*//新增if判斷
JConditional conditionIf = getInstanceBody._if(fieldRef.eq(JExpr
._null()));
JBlock thenPart = conditionIf._then();
thenPart.assign(fieldRef, JExpr._new(cm.parseType(type),)); */
getInstanceBody._return(fieldRef);
//定義成員set方法
JMethod methodSet = dc.method(JMod.PUBLIC, cm.parseType("void"), "set"+name);
//建立set身體
JBlock body = methodSet.body();
//設定set方法引數
methodSet.param(cm.parseType(type), pojo.getColumnName());
JFieldRef ihs = JExpr.ref(pojo.getColumnName());
body.assign(JExpr.refthis(pojo.getColumnName()), ihs);
}
cm.build(file);
}
/**
* 轉換資料型別
* @param dataBaseType
* @return
*/
public String getAbilityType(String dataBaseType) {
//為了保證一致性 一定要忽略大小寫
String lower = dataBaseType.toLowerCase();
if(lower.contains("varchar") || lower.contains("text")) {
return "String";
}else if(lower.contains("int")) {
return "Integer";
}else if(lower.contains("serial")) {
return "Long";
}else if(lower.contains("double")) {
return "Double";
}else if(lower.contains("money")) {
return "BigDecimal";
}else if(lower.contains("date")) {
return "Date";
}else if(lower.contains("boolean")) {
return "Boolean";
}else {
return "String";
}
}
}
⑥測試
package cn.allsales;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import cn.allsales.tools.GenerateEntity;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AllSalesApplicationTests {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driver;
@Autowired
private GenerateEntity generate;
@Test
public void contextLoads() {
try {
generate.getGenerate("tpt_address","Address");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
⑦最終結果
package cn.allsales.entity;
public class Address {
/**
* id
*
*/
private Integer id;
/**
* 使用者uid
*
*/
private Integer useruid;
/**
* 姓名
*
*/
private String username;
/**
* 手機號
*
*/
private String usermobile;
/**
* 地址所屬省
*
*/
private String areaId1;
/**
* 地址所屬市
*
*/
private String areaId2;
/**
* 地址所屬區縣
*
*/
private String areaId3;
/**
* 詳細地址
*
*/
private String addres;
/**
* 郵編
*
*/
private String postCode;
/**
* 是否預設地址,0:否 1:是
*
*/
private Integer isDefault;
/**
* 建立時間
*
*/
private String createTime;
private Address() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUseruid() {
return useruid;
}
public void setUseruid(Integer useruid) {
this.useruid = useruid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsermobile() {
return usermobile;
}
public void setUsermobile(String usermobile) {
this.usermobile = usermobile;
}
public String getAreaId1() {
return areaId1;
}
public void setAreaId1(String areaId1) {
this.areaId1 = areaId1;
}
public String getAreaId2() {
return areaId2;
}
public void setAreaId2(String areaId2) {
this.areaId2 = areaId2;
}
public String getAreaId3() {
return areaId3;
}
public void setAreaId3(String areaId3) {
this.areaId3 = areaId3;
}
public String getAddres() {
return addres;
}
public void setAddres(String addres) {
this.addres = addres;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public Integer getIsDefault() {
return isDefault;
}
public void setIsDefault(Integer isDefault) {
this.isDefault = isDefault;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
}