I want to select an entity Person
from the database (JPA with Hibernate). Person
has has two (or more) oneToMany-Relationships, e.g. Address
and Phone
.
How would I fully restore the instance of Person
and all related entities of Address
and Phone
. E.g. the focal Person has two Addresses and three Phones?
(I can persist
the instance of Person
with one command, but how can I load it?)
@Entity
public class Person implements Serializable {
@Id @GeneratedValue
private int id;
private String name;
@OneToMany(mappedBy="person")
private List<Address> addresses = new ArrayList<Address>();
@OneToMany(mappedBy="person")
private List<Phone> phones = new ArrayList<Phone>(); // plus getter and setter
}
@Entity
public class Address implements Serializable {
@Id @GeneratedValue
private int id;
@ManyToOne
private Person person;
private String onestring; // plus getter and setter
}
@Entity
public class Phone implements Serializable {
@Id @GeneratedValue
private int id;
@ManyToOne
private Person person;
private String anotherstring; // plus getter and setter
}
EDIT: I tried two ways suggested below. First try with calling getter:
@Stateless
public class PersonManager {
@PersistenceContext
private EntityManager em;
public Person getPerson(int id) {
Person person = em.find(Person .class, id);
person.getAddresses ();
person.getPhones();
return person;
}
Result: both lists are not initialized.
Second way:
@NamedQuery(name="PersonAddressesPhones",
query = "SELECT p FROM Person p " +
"left join fetch p.addresses " +
"left join fetch p.phones " +
"WHERE p.id = :id")
Result: This causes the exception:
org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags