JPA @Transient fields being cleared before @PreUpd

2020-07-02 12:13发布

问题:

I have an User Entity class that I'm trying to do password hashing for. I thought that the easiest way to do this would be to create a password field annotated with @Transient and a hashed password field that is set just before the object is persisted with a method annotated with @PrePersist and @PreUpdate.

So I have something like this:

@Transient
private String password;

private String hashedPassword;

@PrePersist
@PreUpdate
private void hashPassword() {
    if(password != null) {
        hashedPassword = PasswordHasher.hashPassword(password);
    }
}

This works perfectly fine when an entity is persisted. The password field is still set by the time hashPassword is called, and a value for hashedPassword is calculated and stored.

However, the same isn't true for an update - even if a new value for password is set just before merging the entity, the field is null by the time hashPassword is called. Why is this? Shouldn't the values of transient fields stick around at least until the entity is persisted?

(I'm using EclipseLink 2.0.0 btw, if it makes any difference)

回答1:

I solved this by setting updatable und insertable to false on the "transient" field, so in your case this would be:

@Column(name = "password", insertable = false, updatable = false)
private String password;

Therefore a table @column is required (which is kind of ugly) but it will never be filled (which was important in my case for security reasons).

I tested against Hibernate 4.3.4.Final and it worked for me. The field value was useable in my EntityLister @PrePersist and @PreUpdate methods but was not stored in the database.

Hope that helps anybody having similar problems.



回答2:

As mentioned in the above answer, this is by design in the spec. EclipseLink contains an event (postMerge) that is not part of the JPA spec that should be called in the right point in the cycle for you. In EclipseLink 2.1 The Descriptor Event Adaptor class can be registered using the regular @EventListeners annotation, pre 2.1 you will need to add the even using EclipseLink native API.

@EntityListeners({
    a.b.MyEventListener.class,
})

package a.b;

import org.eclipse.persistence.descriptors.DescriptorEvent;
import org.eclipse.persistence.descriptors.DescriptorEventAdapter;

public class MyEventListener extends DescriptorEventAdapter {

    public void postMerge(DescriptorEvent event) {
        //event.getSession();
        //event.getObject();
        //event.getOriginalObject();
    }
}