Answer the question
In order to leave comments, you need to log in
Spring Data how to properly setup/save an entity?
@Entity
public class ReportPeriod {
...
@OneToMany(fetch = FetchType.LAZY, mappedBy = "reportPeriod")
private Collection<Document> documents;
}
@Entity
public class Document {
...
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "report_period_id", referencedColumnName = "id", nullable = false)
private ReportPeriod reportPeriod;
}
...
ReportPeriod rp = new ReportPeriod();
rp.setDatePeriod('01.01.2001');
reportPeriodRepository.save(rp);
...
Answer the question
In order to leave comments, you need to log in
The collection will be empty if the object is loaded from the database. If the object was created in code and saved to the database, then Hibernate will not initialize anything.
I usually use the following code for internal collection getters (I peeped from JAXB):
public Collection<Document> getDocuments() {
if (documents == null) {
documents = new ArrayList<>();
}
return documents;
}
rp = reportPeriodRepository.save(rp);
And you will be happy. But it's better to create an empty collection in the get method if needed. In general, it's better to stop using @OneToMany and @ManyToMany collections.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question