JPA调用函数加密解密password字段

在我们使用JPA时,经常会遇到在存取或读取数据库中某一字段的时候需要加密或者解密,例如 password 字段。

Hibernate 框架允许我们自定义一些 sql 表达式来存取和读取列值,方法如下:


import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.hibernate.annotations.ColumnTransformer;
import org.hibernate.annotations.GenericGenerator;

@XmlRootElement
@Entity
@Cacheable
@Table(name = "USER")
public class User {

@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "ID")
private int id;

@Column(name = "NAME")
private String name;

@Column(name = "PASSWORD")
@ColumnTransformer(
read = "decrypt(PASSWORD)",
write = "encrypt(nvl(?, 'null'))"
)
private String password;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}

你可能感兴趣的:(Java,DAO)