L. Young
L. Young

Reputation: 173

JPA, change field value using java on UPDATE/merge

I have an entity with a field updatedUser which keeps track of the user who updated the row values.

When the entity is created this field is null but it should be set when a change is made to the entity and merge is used.

Is there some way, through java, to fill this value only when the entity has been updated? IE: should not be changed if it is created or retrieve from db.

@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
}

Upvotes: 0

Views: 199

Answers (1)

Robert Franz
Robert Franz

Reputation: 543

Updating a value is possbile by using the javax.persistence.PreUpdate annotation. But there is no way to inject the current user. Maybe it is possible to read the user from ThreadLocal and then set the user, but that is not a really clean solution as it must be set before when entering your business code or so ..

Upvotes: 1

Related Questions