S
S
ScRsa2017-03-02 10:56:23
Java
ScRsa, 2017-03-02 10:56:23

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);
...

When creating a new period, I get:
rp.Id = 123
rp.datePeriod = '01/01/2001'
rp.documents = null
Question. Why after saving the period I get that documents == null? In theory, an empty collection should return?
If you search for another previously saved period: reportPeriodRepository.findOne(345). Then rp.getDocuments() returns a collection and not null.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene Khrustalev, 2017-03-02
@ScRsa

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;
}

A
Alexander Kosarev, 2017-03-03
@jaxtr

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 question

Ask a Question

731 491 924 answers to any question