使用反射方式獲取JPA Entity的屬性和值
反射方式獲取JPA Entity屬性和值
在記錄日志或者調(diào)試的時候,往往需要輸出數(shù)據(jù)庫查詢或者寫入的值,或者在接口交互的時候,可能需要將實體轉(zhuǎn)成JSON串傳遞出去。
在JPA中是以Entity的示例方式傳遞的。但是如果直接使用Entity.toString()
方法的話,輸出的結(jié)果是entity@內(nèi)存地址的形式,無法得知Entity的內(nèi)部具體的屬性和值。
以下描述采用反射方式獲取Entity的字段和值的方法:
反射工具類
以將實體轉(zhuǎn)為JSON串為例:
public class ReflectEntity{ public static String toStr(Object o){ try{ StringBuilder sb = new StringBuilder(); sb.append("{"); Class cls = o.getClass(); Field[] fields = cls.getDeclaredFields(); for(Field f : fields){ f.setAccessible(true); sb.append("\"").append(f.getName()).append("\":\"").append(f.get(o)).append("\","); } return String.format("%s}",sb.subString(0,sb.length()-1)); } catch(Exception e){ return null; } } }
重寫toString方法
假設(shè)有個JPA Entity:
@Entity public class E{ ? ? private String colA; ? ? private String colB; ? ? //getter, setter 略 ? ? //在此處使用反射方法即可 ? ? @Override ? ? public String toString(){ ? ? ? ? return ReflectEntity.toStr(this); ? ? } }
通過以上改造后,記錄或者通過網(wǎng)絡(luò)接口調(diào)用傳輸Entity或者List<Entity>都能順利轉(zhuǎn)為JSON串。
通過反射獲取Entity的數(shù)據(jù)
應(yīng)用場景:有些時候SQL比較難拼接(比如說:不確定通過哪個字段獲取數(shù)據(jù)),這個時候我們可以利用java反射來獲取數(shù)據(jù)
1.Entity實體類
@Entity @Table(name = EntitlementDbConstants.CUSTOMER_MASTER_DATA_VIEW) public abstract class CustomerMasterDataView { ? ? private static final long serialVersionUID = 1963275800615627823L;? ? ? @ExtendField ? ? @Column(name = CommonHanaDbExtendsColumnConstants.S_EX_1) ? ? private String sEX1; ? ? ? @ExtendField ? ? @Column(name = CommonHanaDbExtendsColumnConstants.S_EX_2) ? ? private String sEX2; ? ? ? //省略get,set方法 }
2.通過java反射獲取Entity數(shù)據(jù)
private List<Map<String, Object>> getExtensionAttributeValue(List<CustomerMasterDataView> customerMasterDataViews, String field, String type) ? ? { ? ? ? ? List<Object> noRepeakValue = new ArrayList<>(); ? ? ? ? List<Map<String, Object>> valueList =new ArrayList<>(); ? ? ? ? Map<String, Object> map = null; ? ? ? ? Object obj = null; ? ? ? ? String methodName = "get" + StringUtils.uncapitalize(StringUtils.replaceEach(field, new String[] ? ? //通過get方法獲取數(shù)據(jù) ? ? ? ? { "_" }, new String[] ? ? ? ? { "" })); ? ? ? ? for(CustomerMasterDataView customerMasterDataView:customerMasterDataViews) ? ? ? ? { ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? Method method = customerMasterDataView.getClass().getMethod(methodName); ? ? ? ? ? ? ? ? obj = method.invoke(customerMasterDataView);// obj就是我們獲取某個字段的值 ? ? ? ? ? ? } ? ? ? ? ? ? catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? if (logger.isDebugEnabled()) ? ? ? ? ? ? ? ? ? ? logger.debug("Could not reflect the method {}", methodName, e); ? ? ? ? ? ? } ? ? ? ? ? ? map = formatAttributeValue(obj, type, noRepeakValue); ? ?// 格式化數(shù)據(jù),自定義的方法 ? ? ? ? ? ? if(null != map) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? valueList.add(map); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? return valueList; ? ? }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
一篇文章教你將JAVA的RabbitMQz與SpringBoot整合
這篇文章主要介紹了如何將JAVA的RabbitMQz與SpringBoot整合,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2021-09-09java web response提供文件下載功能的實例講解
下面小編就為大家分享一篇java web response提供文件下載功能的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01詳解Springboot應(yīng)用啟動以及關(guān)閉時完成某些操作
這篇文章主要介紹了詳解Springboot應(yīng)用啟動以及關(guān)閉時完成某些操作,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11SpringMVC整合,出現(xiàn)注解沒有起作用的情況處理
這篇文章主要介紹了SpringMVC整合,出現(xiàn)注解沒有起作用的情況及處理,具有很好的參考價值,希望對大家有所幫助。2023-05-05netty服務(wù)端處理請求聯(lián)合pipeline分析
這篇文章主要為大家介紹了netty服務(wù)端處理請求聯(lián)合pipeline示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04Spring實現(xiàn)默認(rèn)標(biāo)簽解析流程
這篇文章主要為大家詳細(xì)介紹了Spring實現(xiàn)默認(rèn)標(biāo)簽解析流程,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01