I have a simple @Entity
with a couple of @ManyToOne
fields. I fetch the child entities from database and want to simply create a new instance of the parent entity and save that to database.
When I call myRepository.save(myParentObject)
though, Hibernate first does a few selects, one for each field annotated with @ManyToOne
, and the logs say very clearly Getting current persistent state for: [...]
. Only once these 2 select operations are completed, the insert finally takes place.
The only solution I found to prevent these undesired select
operations is declaring the ids of the child entities as @GeneratedValue(strategy = GenerationType.IDENTITY)
. I'm using natural ids though, so that doesn't really make sense, and I'd like to avoid that. Implementing Persistable
on the child instances did not make any difference. How do I avoid the unnecessary selects while not using @GeneratedValue
s?
@Entity
public class NewspaperArticle {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotNull @ManyToOne @JoinColumn(name="release")
private ReleaseInfo releaseInfo;
(...)
}
@Entity
@Table(name = "release_info")
public class ReleaseInfo implements Persistable<LocalDate> {
// removing @GeneratedValue here causes an additional fetch to happen
// before a save() on NewspaperArticle happens
@Id @NotNull @GeneratedValue(strategy = GenerationType.IDENTITY)
private LocalDate canonicalDate;
(...)
}
UPDATE
A call like this
Optional<ReleaseInfo> maybeRelease = releaseInfoRepository.findById(<date>);
NewspaperArticle article = new NewspaperArticle();
article.setReleaseInfo(maybeRelease.get());
newspaperArticleRepository.save(article);
would generate these logs