PreUpdate回调中的字段值未被修改 [英] Field values are not being modified on PreUpdate callback

查看:189
本文介绍了PreUpdate回调中的字段值未被修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将以下类定义为默认的实体侦听器,所以每次调用persist()或merge()方法时,这个代码将被自动执行:

I've defined the following class as as default Entity Listener, so every time I call the persist() or merge() methods this code will be executed automatically:

public class StringProcessorListener {

    @PrePersist
    @PreUpdate
    public void formatStrings(Object object) {
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                if (f.getType().equals(String.class)) {
                    f.setAccessible(true);
                    if (f.get(object) != null) {
                        f.set(object, f.get(object).toString().toUpperCase());
                    }
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(StringProcessorListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

这样做的目的是在将对象的所有字符串插入数据库之前,将其大小写。 @PrePersist工作正常,该方法修改所有字符串,并将其保存大写在数据库中,但是当我尝试更新一个对象时,它不能很好地工作,该方法被正常调用,并且还会修改字符串,但是而不是将修改的对象保存在数据库上,它正在保存对象,就像在此方法之前一样。

The purpose of this is to capitalize all the strings of an object before insert it into the database. The @PrePersist worked fine, the method modifies all the strings and it is saved capitalized on the database, but when I try to update an object it didn't work so well, the method is called normally and it also modifies the strings, but instead of saving the modified object on the database, it is saving the object as it was before this method.

有关如何解决这个问题的任何想法?

Any ideas on how to solve this?

更新:

我使用 DescriptorEvent ,它让我可以访问ObjectChangeSet,我可以手动更新它,然后将值正确保存在数据库中。

I solved it using a DescriptorEvent, it gave me access to the ObjectChangeSet and I could update it manually, then the values were correctly saved on the database.

推荐答案

如果在服务器环境中运行或使用代理进行编织,EclipseLink将默认使用更改跟踪,以便出于性能原因。如果是这样,您直接在对象中设置值的方法将绕过编织变形代码,因此EclipseLink不知道更改。 O持久化,它直接从对象使用所有值,而在更新时,它只使用已更改的字段,它只会通过更改的侦听器了解更改。您将需要使用方法访问来设置这些字段,或关闭更改跟踪:
http://eclipse.org/eclipselink/documentation/2.5/jpa/extensions/a_changetracking.htm

If running in a server environment or using an agent for weaving, EclipseLink will default to using change tracking where possible for performance reasons. If so, your method of directly setting the values in the object would bypass the woven changetracking code, so EclipseLink isn't aware of the changes. O persist, it uses all values directly from the object, while on updates, it only uses the changed fields, and it would only know about changes through the changetracking listeners. You will either need to use method access to set these fields, or turn off change tracking: http://eclipse.org/eclipselink/documentation/2.5/jpa/extensions/a_changetracking.htm

这篇关于PreUpdate回调中的字段值未被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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