使用反射更新JPA实体不起作用? [英] Updating JPA entity with reflection does not work?

查看:86
本文介绍了使用反射更新JPA实体不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的实体:(我正在为网页编码,所以我为任何错误道歉)

I have an entity which looks something like this: (I'm coding to the web page so I apologize for any mistakes)

@Entity
public class Entity {
    @Id
    private Long id;
    private String field;

    // Insert getters and setters here...
}

我尝试使用反射来操纵它:

I try to manipulate it using reflection:

Long id = 1;

Entity entity = myDao.getEntity(id);

entity.setField("set directly");

Field[] fields = entity.getClass().getDeclaredFields();

for (Field f : fields) {
    if (f.getName().equals("field")) {
        f.setAccessible(true);
        f.set(entity, "set using reflection");
        f.setAccessible(false);
    }
}

System.out.println(entity.getField());

此程序打印使用反射设置。但是,在数据库中,使用反射设置的值不会更新:

This program prints "set using reflection". However, in the database the value set using reflection does not get updated:

SELECT * FROM ENTITY WHERE ID = 1
ID     FIELD
1      set directly

这很奇怪。我可以发誓这曾经工作 - 但现在不是。难道你不能使用反射来操纵实体吗?

This is strange. I could swear that this used to work - but now it isn't. Is it really so that you cannot manipulate entities using reflection?

如果重要的话,我正在使用EclipseLink 1.1.1。

I'm using EclipseLink 1.1.1 if that matters.

推荐答案

通过反思改变实体类的价值将充满问题。这是因为你正在处理一个持久的类,因此持久性API需要知道对字段的更改。

Changing values of an entity class by reflection is going to fraught with issues. This is because you're dealing with a class which is persistent and thus the persistence API needs to know about changes to the fields.

如果你通过反射进行更改,那么持久性API是否会知道这些更改。

If you make changes via reflection, chances are the persistence API will not know about those changes.

更好的解决方案是通过反射调用setter。

A better solution would be to call the setters via reflection.

这篇关于使用反射更新JPA实体不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆