Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA OneToMany, always empty

i have a bidirectional, one to many, and many to one relationship. say, a Company has many Persons, and a Persons has one company, so, in company,

@OneToMany(mappedBy = "company", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Collection<Person> persons;

and in Person,

@ManyToOne
@JoinColumn(name="COMPANY_ID")
private Company company;

now, say i have a @PrePersist / @PreUpdate method on Company, where when it is updated, i want to set the same timestamp on all the People ... like,

@PrePersist
@PreUpdate
public void setLastModified() {
    this.lastModified = System.currentTimeMillis();
    if (persons != null) {
        for (Person person : persons) {
            person.setLastModified(this.lastModified);
        }
    }
}

when i debug this, i see that the persons field in Company is always empty. when i look at the type of the persons collection, it's a java.util.Vector. not sure if that's relevant. i expected to see some auto-loading JPA collection type.

what am i doing wrong?

like image 951
Jeffrey Blattman Avatar asked Feb 26 '11 00:02

Jeffrey Blattman


2 Answers

You must set both sides of your relationship. When you create a new Person and set its Company you must also add the Person to the Company's persons (employees?).

Also, you should not change another object in one object's prePersist/Update, you should use its own prePersist/Update event.

See, http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Object_corruption.2C_one_side_of_the_relationship_is_not_updated_after_updating_the_other_side

like image 174
James Avatar answered Oct 11 '22 01:10

James


Add fetch = FetchType.Eager to @ManyToOne annotation. You added it on the other side of relationship.

like image 43
anergy Avatar answered Oct 10 '22 23:10

anergy