import junit.framework.Assert;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.junit.Before;
import java.util.List;
public class FetchModeTest {
private SessionFactory factory;
@Before
public void setUp() throws Exception { factory = new Configuration().configure(
"hibernate.cfg.xml").addAnnotatedClass(Citizen.class).addAnnotatedClass(City.class)
.buildSessionFactory();
Session session = factory.openSession();
City berlin = new City("Berlin");
session.save(berlin);
Citizen hans = new Citizen("Hans");
hans.setCity(berlin);
session.save(hans);
berlin.getCitizens().add(hans);
Citizen peter = new Citizen("Peter");
peter.setCity(berlin);
session.save(peter);
berlin.getCitizens().add(peter);
session.save(berlin);
session.flush();
City hamburg = new City("Hamburg");
session.save(hamburg);
Citizen horst = new Citizen("Horst");
horst.setCity(hamburg);
session.save(horst);
Citizen anne = new Citizen("Anne");
anne.setCity(hamburg);
session.save(anne);
hamburg.getCitizens().add(horst);
hamburg.getCitizens().add(anne);
session.close();
factory.getCache().evictEntityRegions(); factory.getCache().evictCollectionRegions(); }
@org.junit.Test public void testWithJoinAndList() throws Exception {
preHeatCacheWithJoinAndList();
Session newSession = factory.openSession();
City berlin = (City) newSession.createCriteria(City.class).add(Restrictions.eq("name", "Berlin")).uniqueResult();
Assert.assertEquals(2, berlin.getCitizens().size());
newSession.close();
}
@org.junit.Test public void testWithJoinAndScroll() throws Exception {
preheatCacheWithJoinAndScroll();
Session newSession = factory.openSession();
City berlin = (City) newSession.createCriteria(City.class).add(Restrictions.eq("name", "Berlin")).uniqueResult();
Assert.assertEquals(2, berlin.getCitizens().size());
newSession.close();
}
private void preHeatCacheWithJoinAndList() {
Session preheatSession = factory.openSession();
List<City> list = preheatSession.createCriteria(City.class).setFetchMode("citizens", FetchMode.JOIN).list();
for (City city : list) {
Hibernate.initialize(city); }
preheatSession.close();
}
private void preheatCacheWithJoinAndScroll() {
Session preheatSession = factory.openSession();
ScrollableResults cursor = preheatSession.createCriteria(City.class).setFetchMode("citizens", FetchMode.JOIN).scroll();
while (cursor.next()) {
City city = (City) cursor.get(0);
Hibernate.initialize(city); }
preheatSession.close();
}
}