Hi,
I'm using the latest Hibernate Entity Manager + Hibernate Annotation packages. I specified a OneToMany relation ship and set the fetch type to lazy on the parent. I enabled the show sql option for hibernate and realized that when I load the parent from the db a second call is made to load the childs. Even if I didn't access the collection. Does this behaves as expected?
Using the Troop/Soldier classes from the annotation project I created the following test.
Code:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1");
EntityTransaction tx;
System.out.println("***Creating troop...");
EntityManager em = emf.createEntityManager();
tx = em.getTransaction();
tx.begin();
Troop disney = new Troop();
disney.setName("Disney");
Soldier mickey = new Soldier();
mickey.setName("Mickey");
disney.addSoldier(mickey);
em.persist(disney);
tx.commit();
em.close();
System.out.println("***Loading troop...");
em = emf.createEntityManager();
tx = em.getTransaction();
tx.begin();
Troop troop = em.find(Troop.class, disney.getId());
tx.commit();
em.close();
The console output is this:
Code:
Creating troop...
Hibernate: /* insert org.hibernate.test.annotations.onetomany.Troop */ insert into Troop (name) values (?)
Hibernate: /* insert org.hibernate.test.annotations.onetomany.Soldier */ insert into Soldier (troop_fk, name) values (?, ?)
Loading troop...
Hibernate: /* load org.hibernate.test.annotations.onetomany.Troop */ select troop0_.id as id3_0_, troop0_.name as name3_0_ from Troop troop0_ where troop0_.id=?
Hibernate: /* load one-to-many org.hibernate.test.annotations.onetomany.Troop.soldiers */ select soldiers0_.troop_fk as troop3_1_, soldiers0_.id as id1_, soldiers0_.id as id2_0_, soldiers0_.troop_fk as troop3_2_0_, soldiers0_.name as name2_0_ from Soldier soldiers0_ where soldiers0_.troop_fk=? order by soldiers0_.name desc
This tells me that even if I specify lazy loading for the collection, the whole collection is loaded when the parent (troop) is loaded.
Did I misunderstood the feature?
Regards,
Johan