Can we update an entity in @PrePersist of another entity
0
votes
0
answers
16
views
Currently I have two entities (Employee, Company) and Employee has many to one relation to company. Company has a field lastPersonJoined and on each Employee insertion, lastPersonJoined in Company entity is updated . This can be implemented in service layer as well but i really want to understand can we do this in @PrePersist or @PostPersist?
When i do the before i didn't face any errors but its not commiting to DB. Correct me if i am wrong i think since company is not managed entity its not saving to DB.
@Entity
public class Employee{
...
@column(name)
public String name;
@ManyToOne(fetch = FetchType.LAZY, optional = false, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
@JoinColumn(name = "id", referencedColumnName = "id", nullable = false)
@ToString.Exclude
private Company company;
@PrePersist
public void prePersist(){
company.setLastManJoined(name);
}
}
Asked by gcs
(1 rep)
May 14, 2025, 04:44 PM
Last activity: May 14, 2025, 04:50 PM
Last activity: May 14, 2025, 04:50 PM