I am using AuditingEntityListener to update creation and last update date of the entity.
@Entity
@Table(name = "MY_ENTITY_TABLE")
@EntityListeners(AuditingEntityListener.class)
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "NAME")
private String name;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "MY_ELEMENTS", joinColumns = @JoinColumn(name = "ENTITY_ID"))
@Fetch(FetchMode.SELECT)
@BatchSize(size=100)
private List<MyElement> elements = new ArrayList<>();
@Column(name = "CREATED_AT", nullable = false)
@JsonFormat(shape = JsonFormat.Shape.STRING)
@CreatedDate
private LocalDateTime createdAt;
@Column(name = "UPDATED_AT", nullable = false)
@JsonFormat(shape = JsonFormat.Shape.STRING)
@LastModifiedDate
private LocalDateTime updatedAt;
}
This works fine and updates updatedAt field to correct value:
// Snippet 1
entity.setName("Entity 1");
entity.setElements(otherElements);
repository.save(entity);
However, when I update only elements, it still updates the elements field just fine, but it does not update updatedAt field:
// Snippet 2
entity.setElements(otherElements);
repository.save(entity);
I have experimented a little with @PrePersist and @PreUpdate hooks. Snippet 1 triggers both hooks, while Snippet 2 triggers neither. It is probably because MY_ELEMENTS table holds the relationship reference and there is actually no need to update anything in MY_ENTITY_TABLE. So, while, I cannot say that this behaviour is technically wrong, I believe it is logically wrong, at least in this case.
Do I have to manually update updatedAt field, or can I make JPA update it somehow?