反射方式获取JPA Entity属性和值
在记录日志或者调试的时候,往往需要输出数据库查询或者写入的值,或者在接口交互的时候,可能需要将实体转成JSON串传递出去。
在JPA中是以Entity的示例方式传递的。但是如果直接使用Entity.toString()
方法的话,输出的结果是entity@内存地址的形式,无法得知Entity的内部具体的属性和值。
以下描述采用反射方式获取Entity的字段和值的方法:
反射工具类
以将实体转为JSON串为例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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方法
假设有个JPA Entity:
1
2
3
4
5
6
7
8
9
10
11
|
@Entity public class E{ private String colA; private String colB; //getter, setter 略 //在此处使用反射方法即可 @Override public String toString(){ return ReflectEntity.toStr( this ); } } |
通过以上改造后,记录或者通过网络接口调用传输Entity或者List<Entity>都能顺利转为JSON串。
通过反射获取Entity的数据
应用场景:有些时候SQL比较难拼接(比如说:不确定通过哪个字段获取数据),这个时候我们可以利用java反射来获取数据
1.Entity实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@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数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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方法获取数据 { "_" }, 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); // 格式化数据,自定义的方法 if ( null != map) { valueList.add(map); } } return valueList; } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/tzdwsy/article/details/47375759