在调用@PreUpdate方法之前,将清除JPA @Transient字段 [英] JPA @Transient fields being cleared before @PreUpdate method is called

查看:213
本文介绍了在调用@PreUpdate方法之前,将清除JPA @Transient字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户实体类,我正在尝试为此进行密码哈希处理。我认为最简单的方法是创建一个用@Transient注释的密码字段,以及一个在对象持久化之前设置的用@PrePersist和@PreUpdate注释的哈希密码字段。

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.

所以我有这样的东西:

@Transient
private String password;

private String hashedPassword;

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

当实体持久存在时,此方法效果很好。密码字段仍在调用hashPassword时设置,并计算并存储hashedPassword的值。

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.

但是,更新并非如此-即使在合并实体之前设置了新的password值,该字段在hashPassword之前也为null叫做。为什么是这样?至少在实体存在之前,瞬态场的值是否应该一直存在?

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?

(我正在使用EclipseLink 2.0.0 btw,如果有区别的话)

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

推荐答案

我通过在瞬态字段上将 updatable insertable 设置为false来解决此问题,因此在您的情况下,应为:

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;

因此需要一个@column表(有点丑陋),但是它永远不会被填充(

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).

我针对Hibernate 4.3.4.Final进行了测试,它对我很有用。该字段值在我的EntityLister @PrePersist和@PreUpdate方法中可用,但未存储在数据库中。

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.

这篇关于在调用@PreUpdate方法之前,将清除JPA @Transient字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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