JPA @Transient fields being cleared before @PreUpdate method is called

robbles picture robbles · Aug 5, 2010 · Viewed 7.2k times · Source

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)

Answer

Jan Ziegler picture Jan Ziegler · Mar 18, 2014

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.