Issue
I have the following entities:
@Entity
public class TableA {
@Id
@GeneratedValue(...)
private Long id;
private Timestamp updatedDateTime;
@Version
private int version;
}
@Entity
public class TableB{
@Id
@GeneratedValue(...)
private Long id;
@ManyToOne
@JoinColumn(name="fieldTableC")
private TableC paymentsData;
}
@Entity
public class TableC{
@Id
@Column(name = "fieldTableC")
private String fieldTableC;
private String someOtherField;
}
The problem I am facing, is that I cannot find any information on how to do the following scenario: If either TableB or TableC gets updated, then I need hibernate to automatically increment the version in TableA. Should I add a FK of TableA to TableB & TableC ? As you can see, I already have a @ManyToOne from TableB to TableC, if that helps in any way. PS: I am using JpaRepository
Solution
I ended up by adding the child reference in parent, and parent reference into child. Whenever I want to save a child, I also update the parent updatedDateTime value. My method is @Transient, so everything will be saved in 1 transaction.
Also added CascadeType.SAVE_UPDATE, so that when saving parent, the child will also be saved
Eg: Added to TableA:
@OneToMany(mappedBy = "tableA")
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
private List<TableB> list= new ArrayList<>();
Added to TableB:
@ManyToOne
@JoinColumn(name = "tableA_root_id")
private TableA tableA;
Answered By - Alex