I noticed that the TopLink essentials implementation of the JPA seems to
allow lazy loading outside a persistence context.
e.g. If I have a one-to-one mapping to an child entity defined as such:
@OneToOne(fetch=FetchType.LAZY)
private Ringtone ringtone;
then I can load the parent objects within an EntityManager/transaction,
commit the transaction, close the EntityManager and still lazily load
the ringtone.
e.g.
EntityManager manager = factory.createEntityManager();
EntityTransaction tx = manager.getTransaction();
tx.begin();
Query query = manager.createQuery("select p from Person p");
List<Person> results = (List<Person>)query.getResultList();
tx.commit();
manager.close();
for (Person p : results) {
System.out.println("got a person: " + p); // toString
calls getRingtone
}
Is this behaviour defined by the spec? It does not work with the
Hibernate implementation because that implementation seems to explicitly
exclude accessing any lazy loading outside an EntityManager session.
There is lots of discussion about this type of behaviour with the
Hibernate core implementation and they believe it is not advisable for
many reasons. So I'm wondering if this is considered a bug in the
TopLink implementation or an implementation specific detail?
Environment:
jdk1.5.0_07
Glassfish Persistence v2-b21
Hibernate 3.2.0
Derby 10.1.3.1
Here is the Hibernate exception:
Exception in thread "main" org.hibernate.LazyInitializationException:
could not initialize proxy - the owning Session was closed
at
org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:60)
And here is my Person class:
// Full definition of Person
@Entity
public class Person implements Serializable {
@Id @GeneratedValue
public Long id;
public String firstName;
public String middleName;
public String lastName;
@OneToOne(fetch=FetchType.LAZY)
private Ringtone ringtone;
public Ringtone getRingtone() {
return this.ringtone;
}
public void setRingtone(Ringtone ringtone) {
this.ringtone = ringtone;
}
public String toString() {
return "First: " + firstName
+ " Middle: " + middleName
+ " Last: " + lastName
+ " Ringtone: " + ringtone;
}
}
Thanks
Martin Bayly