Hi, I am very new to Hibernate and JPA. I am using Hibernate 3.3 with Hibernate annotation 3.4, and I tried to use JPA as much as I could unless the features are missing in JPA (such as CollectionId). I have been fighting with the following mapping problem for a while. I think this should be a basic mapping requirement, yet, I could not resolve it...
I have a Person entity table, mapping to a person table. Since a person might have multiple addresses, I want to map a collection of addresses to this Person by using CollectionOfElements annotation. However, each time when I retrieve the person object out, the collection of addresses are always empty (even with eager fetch), though the generated SQL looks fine to me..
This is my Person class:
@Entity
public class Person {
private long emplId;
private List<Address> addresses = new ArrayList<Address>();
@Id
public long getEmplId(){
return emplId;
}
@org.hibernate.annotations.CollectionOfElements (fetch=FetchType.EAGER)
@JoinTable(
name="ADDRESSES",
joinColumns = @JoinColumn(name="EMPL_ID")
)
@org.hibernate.annotations.CollectionId(
columns = @Column(name="ID"),
type = @org.hibernate.annotations.Type (type = "long"),
generator = "sequence")
public List<Address> getAddresses(){
return addresses;
}
// setters and other properties omitted here
}
Then, I have an embeddable Address class
@Embeddable
public class Address {
private Person person;
private String addressTypeCd;
private String addressLine;
@org.hibernate.annotations.Parent
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
The generated SQL is:
Hibernate: select person0_.EMPL_ID as EMPL1_5_0_, ......, addresses1_.EMPL_ID as EMPL1_2_, addresses1_.city as
city2_, addresses1_.TYPE_CD as TYPE12_2_,
from PEOPLE person0_ left outer join ADDRESSES address es1_ on person0_.EMPL_ID=addresses1_.EMPL_ID where person0_.EMPL_ID=?
The SQL looks fine to me. However, when I tried to access person.getAddresses(), the list is empty. Could anyone point to me what the problem is here? I started off using lazy fetch type and doesn't set parent reference in my Address class, but it's not working, so I change the fetch type to eager and add parent reference in Address class. It's still not working:-( One moer thing is that in fact, my Person class is a root class for a hierarchical structure (inheritance type is table per concrete class), and when I tried to use the general Person type as parent in Address class, I got the complaint that it could not figure out the type of Person... hence, I tried to avoid to have the parent reference in my Address class... I think the mistake I made must be very obvious for an experienced Hibernate developers, and I appreciate very much for any insights you might have. Thanks!
|