我有一个带有字段updatedUser
的实体,它跟踪更新行值的用户。
创建实体时,此字段为空,但在对实体进行更改并使用合并
时应设置该字段。
是否有某种方法,通过java,仅在实体更新时才填充此值? IE:如果是创建的或从数据库检索的,则不应更改。
@Entity
@Table(name="employees", uniqueConstraints= {
@UniqueConstraint(columnNames="idEmployees"),
@UniqueConstraint(columnNames="idCardNumber"),
@UniqueConstraint(columnNames="niNumber")
})
public class Employee {
@Id
@GeneratedValue
@Column(unique=true, nullable=false, updatable=false)
private int idEmployees;
//other class variables
@ManyToOne(cascade=CascadeType.PERSIST, fetch=FetchType.LAZY)
@JoinColumn(name="updatedEmployeeId")
private Employee updatedEmployee;
//constructors, getters and setters
}
最佳答案
可以使用 javax.persistence.PreUpdate 注释来更新值。但没有办法注入(inject)当前用户。也许可以从 ThreadLocal 读取用户,然后设置用户,但这不是一个真正干净的解决方案,因为它必须在输入业务代码等之前设置..
关于java - JPA,在更新/合并时使用 java 更改字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25856764/