软件编程
位置:首页>> 软件编程>> java编程>> 使用反射方式获取JPA Entity的属性和值

使用反射方式获取JPA Entity的属性和值

作者:嗡汤圆  发布时间:2023-07-24 17:43:22 

标签:反射,JPA,Entity,属性

反射方式获取JPA Entity属性和值

在记录日志或者调试的时候,往往需要输出数据库查询或者写入的值,或者在接 * 互的时候,可能需要将实体转成JSON串传递出去。

在JPA中是以Entity的示例方式传递的。但是如果直接使用Entity.toString()

方法的话,输出的结果是entity@内存地址的形式,无法得知Entity的内部具体的属性和值。

以下描述采用反射方式获取Entity的字段和值的方法:

反射工具类

以将实体转为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方法

假设有个JPA Entity:

@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实体类

@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数据

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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com