I'm working with Spring Boot 1.5.2.RELEASE and a PostgreSQL 9.5 database.
File entity:
@Entity
public class File implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String externalUid;
}
File repository looks like:
public interface FileRepository extends JpaRepository<File, Long> {
@Modifying
@Query("UPDATE File f SET f.externalUid =:externalUid WHERE f.id =:id")
void setExternalLink(@Param("id") Long id, @Param("externalUid") String externalId);
}
After when I save new file (with flush) and execute update on it, then get this file from repository, then I have outdated entity. But when I have executed clear()
[1] on entityManager
before executing modifying query, then I get the updated entity:
String externalUid = UUID.randomUUID().toString();
File file = new File();
File savedFile = fileRepository.saveAndFlush(file);
// [1] entityManager.clear();
fileRepository.setExternalLink(savedFile.getId(), externalUid);
File updatedFile = fileRepository.findOne(savedFile.getId());
System.out.print(updatedFile.getExternalUid()); // null
This issue quite similar with this one: Spring Boot Data JPA - Modifying update query - Refresh persistence context. But in my case I execute saveAndFlush()
instead of save()
.
In that regard can somebody explain me why we need to clear persistence context before executing modifying query and why repository returns me the outdated entity?