views:

77

answers:

1

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  A: 

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();
    }
}
Peter Krogh