I am having a problem with fetching data that was lazilly initialized
Using Hibernate 3.2.2.ga
A Contact "has an" Address. The getAddress in the Contact class is lazilly initialized. The way I understand this is that If I load the Contact, the Address will not be loaded. If I were to call the getAddress method explicitly, then I am expecting the Address to be loaded.
Code:
@Entity
@Table(name="contact")
public class Contact implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getContactId() {
return contactId;
}
@OneToOne(cascade = {CascadeType.ALL}, fetch=FetchType.LAZY)
@JoinColumn(name = "address_addressId")
public Address getAddress() {
return address;
}
}
@Entity
@Table(name="address")
public class Address implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getAddressId() {
return addressId;
}
@OneToOne
@JoinColumn(name="contact_contactId")
public Contact getContact() {
return contact;
}
}
Here is the Data Access method for the ContactCode:
public static Contact createContact(Contact contactToCreate) {
EntityManager mgr = HibernateUtil.getEntityManager();
try {
mgr.getTransaction().begin();
mgr.persist(contactToCreate); // Persist the new Contact
mgr.getTransaction().commit(); // Make it so.
}
catch (HibernateException e) {
e.printStackTrace();
contactToCreate = null;
}
return contactToCreate;
}
Here is the Data Access method for the AddressCode:
public static Address createAddress(Address newAddress) {
EntityManager mgr = HibernateUtil.getEntityManager();
try {
mgr.getTransaction().begin();
mgr.persist(newAddress); // Persist the new Address
mgr.getTransaction().commit(); // Make it so.
}
catch (HibernateException e) {
e.printStackTrace();
newAddress = null;
}
return newAddress;
}
Here is my JUnit 1.4 test caseCode:
@Test
public void testCreateContactWithAddress() {
Contact c = new Contact();
c.setFirstName("John");
Address a = new Address();
a.setAddrLine1(" 1600 Pennsylvania Avenue NW");
c.setAddress(a);
Contact contact = Contact.createContact(c);
Long id = contact.getContactId();
Contact retrieveContact = Contact.getContact(id);
// The 'address' field as NOT included in the equals()or hashCode() methods so this is successful
assertEquals(contact, retrieveContact);
assertNotSame(contact, retrieveContact);
// Here is where it fails
assertEquals(contact.getAddress(),retrieveContact.getAddress());
assertNotSame(contact.getAddress(), retrieveContact.getAddress());
}
Please see the "Here is where it fails" in the Unit Test.
Why is it that the getAddress does not force the fetch of the Address? Any Ideas?