Java Code Examples for org.hibernate.Session#clear()

The following examples show how to use org.hibernate.Session#clear() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseAbstractDAO.java    From oim-fx with MIT License 6 votes vote down vote up
public <T> void updateList(final List<T> list) {
	if (null != list) {
		Session session = sessionBox.getCurrentSession();
		Transaction transaction = session.beginTransaction();
		try {
			int batch = 0;
			for (Object o : list) {
				session.update(o);
				batch++;
				if (batch == 50) {// 每50条批量提交一次。
					session.flush();
					session.clear();
					batch = 0;
				}
			}
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
		}
	}
}
 
Example 2
Source File: AppResource.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * The @GET annotation causes this method to be invoked whenever an HTTP GET request is received for 
 * the registered URL. 
 */
@GET
public App getAppData( @PathParam("appId") Long appId ) {
	
	// Start a Hibernate session, using the Hibernate SessionFactory created by MasterNodeInitializer or SlaveNodeInitializer.
	String mode = (String) context.getAttribute("mode");
	Session session = mode.equals("master") ? MasterNodeInitializer.openSession() : SlaveNodeInitializer.openSession();
	session.beginTransaction();
	
	// Fetch an App for the given ID, using eager fetching.  The conversion to JSON happens after the 
	// Hibernate Session is closed... so if lazy fetching were used, then the JSON converter would fail 
	// when trying to access associated objects.
	Criteria criteria = session.createCriteria(App.class);
	criteria.add( Restrictions.eq("id", appId) );
	criteria.setFetchMode("supportedDevices", FetchMode.SELECT);
	criteria.setFetchMode("customerReviews", FetchMode.SELECT);
	App app = (App) criteria.uniqueResult();
	
	// Cleanup Hibernate
	session.getTransaction().commit();
	session.clear();
	session.close();
	
	return app;
}
 
Example 3
Source File: ResultCheckStyleTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testInsertionFailureWithParamChecking() {
	Session s = openSession();
	s.beginTransaction();
	ParamCheckingEntity e = new ParamCheckingEntity();
	e.setName( "dummy" );
	s.save( e );
	try {
		s.flush();
		fail( "expection flush failure!" );
	}
	catch( HibernateException ex ) {
		// these should specifically be HibernateExceptions...
	}
	s.clear();
	s.getTransaction().commit();
	s.close();
}
 
Example 4
Source File: ASTParserLoadingTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testInitProxy() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Mammal plat = new Mammal();
	plat.setBodyWeight( 11f );
	plat.setDescription( "Platypus" );
	s.persist( plat );
	s.flush();
	s.clear();
	plat = (Mammal) s.load(Mammal.class, plat.getId() );
	assertFalse( Hibernate.isInitialized(plat) );
	Object plat2 = s.createQuery("from Animal a").uniqueResult();
	assertSame(plat, plat2);
	assertTrue( Hibernate.isInitialized(plat) );
	s.delete(plat);
	t.commit();
	s.close();
}
 
Example 5
Source File: testDB.java    From ALLGO with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
/*	EventAddVo ui = new EventAddVo(12312321,"好的好的!!!",DateTimeUtil.currentTime(),4324324);
	Session s = HibernateSessionFactory.getSession();
	Transaction t = s.beginTransaction();
	s.save(ui);
	t.commit();
	System.out.println("恭喜,第一个Hibernate程序运行成功,记录已插入数据表db_eventadd中!");
	s.close();*/
	
	Session session=HibernateSessionFactory.getSession();
	session.clear();
	String hql="from UserDataVo as user where user.uname=:uname and user.upassword=:upassword";
	Query query=session.createQuery(hql);
	query.setString("uname", "bboxhe");
	query.setString("upassword", "123456");
	List list=query.list();
	System.out.println("login==>"+((UserDataVo)list.get(0)).toString());

}
 
Example 6
Source File: TimeLineDAOimpl.java    From ALLGO with Apache License 2.0 6 votes vote down vote up
@Override
public List<EventVo> getFollowEvent(int uid, int page, int pagenum) {
	List<EventVo> listVo = null;
	Session session=HibernateSessionFactory.getSession();
	session.clear();
	String hql="select vo.eid from EventFollowerVo vo where vo.uid=:uid";
	Query query=session.createQuery(hql);
	query.setParameter("uid",uid);
	query.setFirstResult((page-1)*pagenum);
	query.setMaxResults(pagenum);
	List list = query.list();
	for(int i=0;i<list.size();i++){
		int eid = (int) list.get(i);
		String hql2="from EventVo vo where vo.eid=:eid";
		Query query2=session.createQuery(hql2);
		query2.setParameter("eid",eid);
		if(listVo == null){
			listVo = new ArrayList<EventVo>();
		}
		listVo.addAll(query2.list());
	}
	if(listVo ==null||listVo.size() == 0){
		list = null;
	}
	return listVo;
}
 
Example 7
Source File: TimeLineDAOimpl.java    From ALLGO with Apache License 2.0 6 votes vote down vote up
@Override
public List<EventVo> getUserEvent(int uid, int page, int pagenum) {
	List<EventVo> list=null;

	Session session=HibernateSessionFactory.getSession();
	session.clear();
	String hql="from EventVo vo where vo.uid=:uid and vo.visible=0";
	Query query=session.createQuery(hql);
	query.setParameter("uid",uid);
	query.setFirstResult((page-1)*pagenum);
	query.setMaxResults(pagenum);
	list=query.list();
	if(list ==null||list.size() == 0){
		list = null;
	}

	return list;
}
 
Example 8
Source File: DefaultPersistManager.java    From onedev with MIT License 5 votes vote down vote up
@Sessional
@Override
public void importData(Metadata metadata, File dataDir) {
	Session session = dao.getSession();
	List<Class<?>> entityTypes = getEntityTypes(sessionFactory);
	Collections.reverse(entityTypes);
	for (Class<?> entityType: entityTypes) {
		File[] dataFiles = dataDir.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				return name.startsWith(entityType.getSimpleName() + "s.xml");
			}
			
		});
		for (File file: dataFiles) {
			Transaction transaction = session.beginTransaction();
			try {
				logger.info("Importing from data file '" + file.getName() + "'...");
				VersionedXmlDoc dom = VersionedXmlDoc.fromFile(file);
				
				for (Element element: dom.getRootElement().elements()) {
					element.detach();
					AbstractEntity entity = (AbstractEntity) new VersionedXmlDoc(DocumentHelper.createDocument(element)).toBean();
					session.replicate(entity, ReplicationMode.EXCEPTION);
				}
				session.flush();
				session.clear();
				transaction.commit();
			} catch (Exception e) {
				transaction.rollback();
				throw ExceptionUtils.unchecked(e);
			}
		}
	}	
}
 
Example 9
Source File: RowIdTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testRowId() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Point p = new Point( new BigDecimal(1.0), new BigDecimal(1.0) );
	s.persist(p);
	t.commit();
	s.clear();
	
	t = s.beginTransaction();
	p = (Point) s.createCriteria(Point.class).uniqueResult();
	p.setDescription("new desc");
	t.commit();
	s.clear();
	
	t = s.beginTransaction();
	p = (Point) s.createQuery("from Point").uniqueResult();
	p.setDescription("new new desc");
	t.commit();
	s.clear();
	
	t = s.beginTransaction();
	p = (Point) s.get(Point.class, p);
	p.setDescription("new new new desc");
	t.commit();
	s.close();
	
}
 
Example 10
Source File: UnionSubclassTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testUnionSubclassFetchMode() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Location mel = new Location("Earth");
	s.save(mel);
	
	Human gavin = new Human();
	gavin.setIdentity("gavin");
	gavin.setSex('M');
	gavin.setLocation(mel);
	mel.addBeing(gavin);
	Human max = new Human();
	max.setIdentity("max");
	max.setSex('M');
	max.setLocation(mel);
	mel.addBeing(gavin);
	
	s.flush();
	s.clear();
	
	List list = s.createCriteria(Human.class)
		.setFetchMode("location", FetchMode.JOIN)
		.setFetchMode("location.beings", FetchMode.JOIN)
		.list();
	
	for (int i=0; i<list.size(); i++ ) {
		Human h = (Human) list.get(i);
		assertTrue( Hibernate.isInitialized( h.getLocation() ) );
		assertTrue( Hibernate.isInitialized( h.getLocation().getBeings() ) );
		s.delete(h);
	}
	s.delete( s.get( Location.class, new Long(mel.getId()) ) );
	t.commit();
	s.close();
	
	
}
 
Example 11
Source File: SessionStatsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testSessionStatistics() throws Exception {
	Session s = openSession();
	Transaction tx = s.beginTransaction();
	Statistics stats = getSessions().getStatistics();
	stats.clear();
	boolean isStats = stats.isStatisticsEnabled();
	stats.setStatisticsEnabled(true);
	Continent europe = fillDb(s);
	tx.commit();
	s.clear();
	tx = s.beginTransaction();
	SessionStatistics sessionStats = s.getStatistics();
	assertEquals( 0, sessionStats.getEntityKeys().size() );
	assertEquals( 0, sessionStats.getEntityCount() );
	assertEquals( 0, sessionStats.getCollectionKeys().size() );
	assertEquals( 0, sessionStats.getCollectionCount() );
	europe = (Continent) s.get( Continent.class, europe.getId() );
	Hibernate.initialize( europe.getCountries() );
	Hibernate.initialize( europe.getCountries().iterator().next() );
	assertEquals( 2, sessionStats.getEntityKeys().size() );
	assertEquals( 2, sessionStats.getEntityCount() );
	assertEquals( 1, sessionStats.getCollectionKeys().size() );
	assertEquals( 1, sessionStats.getCollectionCount() );
	tx.commit();
	s.close();

	stats.setStatisticsEnabled( isStats);

}
 
Example 12
Source File: PropertyRefTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testNonLazyBagKeyPropertyRef() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Person p = new Person();
	p.setName( "Steve" );
	p.setUserId( "steve" );
	p.getSystems().add( "QA" );
	p.getSystems().add( "R&D" );
	s.persist( p );
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	s.createQuery( "from Person" ).list();
	s.clear();
	s.createSQLQuery( "select {p.*} from PROPREF_PERS {p}" )
			.addEntity( "p", Person.class.getName() )
			.list();
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	List results = s.createQuery( "from Person" ).list();
	Iterator itr = results.iterator();
	while ( itr.hasNext() ) {
		s.delete( itr.next() );
	}
	t.commit();
	s.close();
}
 
Example 13
Source File: EventDAOimpl.java    From ALLGO with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<EventAddVo> getAdd(int eid) {
	List<EventAddVo> list=null;

	Session session=HibernateSessionFactory.getSession();
	session.clear();
	String hql="from EventAddVo vo where vo.eid=?";
	Query query=session.createQuery(hql);
	query.setParameter(0,eid);

	list=query.list();
	
	return list;
}
 
Example 14
Source File: CaptureOperationsModule.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Processes the given document and stores the events to db.
 */
private void processEvents(Session session, Document document) throws DOMException, SAXException,
        InvalidFormatException {
    NodeList eventList = document.getElementsByTagName("EventList");
    NodeList events = eventList.item(0).getChildNodes();

    // walk through all supplied events
    int eventCount = 0;
    for (int i = 0; i < events.getLength(); i++) {
        Node eventNode = events.item(i);
        String nodeName = eventNode.getNodeName();

        if (nodeName.equals(EpcisConstants.OBJECT_EVENT) || nodeName.equals(EpcisConstants.AGGREGATION_EVENT)
                || nodeName.equals(EpcisConstants.QUANTITY_EVENT)
                || nodeName.equals(EpcisConstants.TRANSACTION_EVENT)) {
            LOG.debug("processing event " + i + ": '" + nodeName + "'.");
            handleEvent(session, eventNode, nodeName);
            eventCount++;
            if (eventCount % 50 == 0) {
                session.flush();
                session.clear();
            }
        } else if (!nodeName.equals("#text") && !nodeName.equals("#comment")) {
            throw new SAXException("Encountered unknown event '" + nodeName + "'.");
        }
    }
}
 
Example 15
Source File: UnionSubclassTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testUnionSubclassOneToMany() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Location mel = new Location("Melbourne, Australia");
	Location mars = new Location("Mars");
	s.save(mel);
	s.save(mars);
	
	Human gavin = new Human();
	gavin.setIdentity("gavin");
	gavin.setSex('M');
	gavin.setLocation(mel);
	mel.addBeing(gavin);
	
	Alien x23y4 = new Alien();
	x23y4.setIdentity("x23y4$$hu%3");
	x23y4.setLocation(mars);
	x23y4.setSpecies("martian");
	mars.addBeing(x23y4);
	
	Alien yy3dk = new Alien();
	yy3dk.setIdentity("yy3dk&*!!!");
	yy3dk.setLocation(mars);
	yy3dk.setSpecies("martian");
	mars.addBeing(yy3dk);
	
	Hive hive = new Hive();
	hive.setLocation(mars);
	hive.getMembers().add(x23y4);
	x23y4.setHive(hive);
	hive.getMembers().add(yy3dk);
	yy3dk.setHive(hive);
	s.persist(hive);
	
	yy3dk.getHivemates().add(x23y4);
	x23y4.getHivemates().add(yy3dk);
	
	s.flush();
	s.clear();
	
	hive = (Hive) s.createQuery("from Hive h").uniqueResult();
	assertFalse( Hibernate.isInitialized( hive.getMembers() ) );
	assertEquals( hive.getMembers().size(), 2 );
	
	s.clear();
	
	hive = (Hive) s.createQuery("from Hive h left join fetch h.location left join fetch h.members").uniqueResult();
	assertTrue( Hibernate.isInitialized( hive.getMembers() ) );
	assertEquals( hive.getMembers().size(), 2 );
	
	s.clear();
	
	x23y4 = (Alien) s.createQuery("from Alien a left join fetch a.hivemates where a.identity like 'x%'").uniqueResult();
	assertTrue( Hibernate.isInitialized( x23y4.getHivemates() ) );
	assertEquals( x23y4.getHivemates().size(), 1 );
	
	s.clear();
	
	x23y4 = (Alien) s.createQuery("from Alien a where a.identity like 'x%'").uniqueResult();
	assertFalse( Hibernate.isInitialized( x23y4.getHivemates() ) );
	assertEquals( x23y4.getHivemates().size(), 1 );
	
	s.clear();
	
	x23y4 = (Alien) s.createCriteria(Alien.class).addOrder( Order.asc("identity") ).list().get(0);
	s.delete( x23y4.getHive() );
	s.delete( s.get(Location.class, new Long( mel.getId() ) ) );
	s.delete( s.get(Location.class, new Long( mars.getId() ) ) );
	assertTrue( s.createQuery("from Being").list().isEmpty() );
	t.commit();
	s.close();
}
 
Example 16
Source File: ManyToOneTest.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testBiDirManyToOneInsertUpdateFalse() throws Exception {
	final Session session = openSession();
	Transaction tx = session.beginTransaction();
	Beer hoegaarden = new Beer();
	Brewery hoeBrewery = new Brewery();
	hoeBrewery.getBeers().add( hoegaarden );
	hoegaarden.setBrewery( hoeBrewery );
	session.persist( hoeBrewery );
	tx.commit();
	session.clear();

	tx = session.beginTransaction();
	hoegaarden = get( session, Beer.class, hoegaarden.getId() );
	assertThat( hoegaarden ).isNotNull();
	assertThat( hoegaarden.getBrewery() ).isNotNull();
	assertThat( hoegaarden.getBrewery().getBeers() )
		.hasSize( 1 )
		.containsOnly( hoegaarden );
	Beer citron = new Beer();
	hoeBrewery = hoegaarden.getBrewery();
	hoeBrewery.getBeers().remove( hoegaarden );
	hoeBrewery.getBeers().add( citron );
	citron.setBrewery( hoeBrewery );
	session.delete( hoegaarden );
	tx.commit();

	session.clear();

	tx = session.beginTransaction();
	citron = get( session, Beer.class, citron.getId() );
	assertThat( citron.getBrewery().getBeers() )
		.hasSize( 1 )
		.containsOnly( citron );
	hoeBrewery = citron.getBrewery();
	citron.setBrewery( null );
	hoeBrewery.getBeers().clear();
	session.delete( citron );
	session.delete( hoeBrewery );
	tx.commit();

	session.close();

	checkCleanCache();
}
 
Example 17
Source File: UnionSubclassTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testUnionSubclassManyToOne() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Location mel = new Location("Melbourne, Australia");
	Location mars = new Location("Mars");
	s.save(mel);
	s.save(mars);
	
	Human gavin = new Human();
	gavin.setIdentity("gavin");
	gavin.setSex('M');
	gavin.setLocation(mel);
	mel.addBeing(gavin);
	
	Alien x23y4 = new Alien();
	x23y4.setIdentity("x23y4$$hu%3");
	x23y4.setLocation(mars);
	x23y4.setSpecies("martian");
	mars.addBeing(x23y4);
	
	Hive hive = new Hive();
	hive.setLocation(mars);
	hive.getMembers().add(x23y4);
	x23y4.setHive(hive);
	s.persist(hive);
	
	Thing thing = new Thing();
	thing.setDescription("some thing");
	thing.setOwner(gavin);
	gavin.getThings().add(thing);
	s.save(thing);
	s.flush();
	
	s.clear();
	
	thing = (Thing) s.createQuery("from Thing t left join fetch t.owner").uniqueResult();
	assertTrue( Hibernate.isInitialized( thing.getOwner() ) );
	assertEquals( thing.getOwner().getIdentity(), "gavin" );
	s.clear();
	
	thing = (Thing) s.createQuery("select t from Thing t left join t.owner where t.owner.identity='gavin'").uniqueResult();
	assertFalse( Hibernate.isInitialized( thing.getOwner() ) );
	assertEquals( thing.getOwner().getIdentity(), "gavin" );
	s.clear();
	
	gavin = (Human) s.createQuery("from Human h left join fetch h.things").uniqueResult();
	assertTrue( Hibernate.isInitialized( gavin.getThings() ) );
	assertEquals( ( (Thing) gavin.getThings().get(0) ).getDescription(), "some thing" );
	s.clear();
	
	assertTrue( s.createQuery("from Being b left join fetch b.things").list().size()==2 );
	s.clear();
	
	gavin = (Human) s.createQuery("from Being b join fetch b.things").uniqueResult();
	assertTrue( Hibernate.isInitialized( gavin.getThings() ) );
	assertEquals( ( (Thing) gavin.getThings().get(0) ).getDescription(), "some thing" );
	s.clear();
	
	gavin = (Human) s.createQuery("select h from Human h join h.things t where t.description='some thing'").uniqueResult();
	assertFalse( Hibernate.isInitialized( gavin.getThings() ) );
	assertEquals( ( (Thing) gavin.getThings().get(0) ).getDescription(), "some thing" );
	s.clear();
	
	gavin = (Human) s.createQuery("select b from Being b join b.things t where t.description='some thing'").uniqueResult();
	assertFalse( Hibernate.isInitialized( gavin.getThings() ) );
	assertEquals( ( (Thing) gavin.getThings().get(0) ).getDescription(), "some thing" );
	s.clear();
	
	thing = (Thing) s.get( Thing.class, new Long( thing.getId() ) );
	assertFalse( Hibernate.isInitialized( thing.getOwner() ) );
	assertEquals( thing.getOwner().getIdentity(), "gavin" );
	
	thing.getOwner().getThings().remove(thing);
	thing.setOwner(x23y4);
	x23y4.getThings().add(thing);
	
	s.flush();
	
	s.clear();

	thing = (Thing) s.get( Thing.class, new Long( thing.getId() ) );
	assertFalse( Hibernate.isInitialized( thing.getOwner() ) );
	assertEquals( thing.getOwner().getIdentity(), "x23y4$$hu%3" );
	
	s.delete(thing);
	x23y4 = (Alien) s.createCriteria(Alien.class).uniqueResult();
	s.delete( x23y4.getHive() );
	s.delete( s.get(Location.class, new Long( mel.getId() ) ) );
	s.delete( s.get(Location.class, new Long( mars.getId() ) ) );
	assertTrue( s.createQuery("from Being").list().isEmpty() );
	t.commit();
	s.close();
}
 
Example 18
Source File: HibernateCacheExample.java    From journaldev with MIT License 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	
	SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
	Session session = sessionFactory.getCurrentSession();
	Transaction tx = session.beginTransaction();
	
	//Get employee with id=1
	Employee emp = (Employee) session.load(Employee.class, new Long(1));
	printData(emp,1);
	
	//waiting for sometime to change the data in backend
	Thread.sleep(10000);
	
	//Fetch same data again, check logs that no query fired
	Employee emp1 = (Employee) session.load(Employee.class, new Long(1));
	printData(emp1,2);
	
	//Create new session
	Session newSession = sessionFactory.openSession();
	//Get employee with id=1, notice the logs for query
	Employee emp2 = (Employee) newSession.load(Employee.class, new Long(1));
	printData(emp2,3);
	
	//START: evict example to remove specific object from hibernate first level cache
	//Get employee with id=2, first time hence query in logs
	Employee emp3 = (Employee) session.load(Employee.class, new Long(2));
	printData(emp3,4);
	
	//evict the employee object with id=1
	session.evict(emp);
	System.out.println("Session Contains Employee with id=1?"+session.contains(emp));

	//since object is removed from first level cache, you will see query in logs
	Employee emp4 = (Employee) session.load(Employee.class, new Long(1));
	printData(emp4,5);
	
	//this object is still present, so you won't see query in logs
	Employee emp5 = (Employee) session.load(Employee.class, new Long(2));
	printData(emp5,6);
	//END: evict example
	
	//START: clear example to remove everything from first level cache
	session.clear();
	Employee emp6 = (Employee) session.load(Employee.class, new Long(1));
	printData(emp6,7);
	Employee emp7 = (Employee) session.load(Employee.class, new Long(2));
	printData(emp7,8);
	
	System.out.println("Session Contains Employee with id=2?"+session.contains(emp7));
	
	tx.commit();
	sessionFactory.close();
}
 
Example 19
Source File: StatsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testCollectionFetchVsLoad() throws Exception {
	Statistics stats = getSessions().getStatistics();
	stats.clear();

	Session s = openSession();
	Transaction tx = s.beginTransaction();
	Continent europe = fillDb(s);
	tx.commit();
	s.clear();

	tx = s.beginTransaction();
	assertEquals(0, stats.getCollectionLoadCount() );
	assertEquals(0,  stats.getCollectionFetchCount() );
	Continent europe2 = (Continent) s.get( Continent.class, europe.getId() );
	assertEquals("Lazy true: no collection should be loaded", 0, stats.getCollectionLoadCount() );
	assertEquals( 0, stats.getCollectionFetchCount() );
	europe2.getCountries().size();
	assertEquals( 1, stats.getCollectionLoadCount() );
	assertEquals("Explicit fetch of the collection state", 1, stats.getCollectionFetchCount() );
	tx.commit();
	s.close();

	s = openSession();
	tx = s.beginTransaction();
	stats.clear();
	europe = fillDb(s);
	tx.commit();
	s.clear();
	tx = s.beginTransaction();
	assertEquals( 0, stats.getCollectionLoadCount() );
	assertEquals( 0, stats.getCollectionFetchCount() );
	europe2 = (Continent) s.createQuery(
			"from " + Continent.class.getName() + " a join fetch a.countries where a.id = " + europe.getId()
		).uniqueResult();
	assertEquals( 1, stats.getCollectionLoadCount() );
	assertEquals( "collection should be loaded in the same query as its parent", 0, stats.getCollectionFetchCount() );
	tx.commit();
	s.close();

	Collection coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
	coll.setFetchMode(FetchMode.JOIN);
	coll.setLazy(false);
	SessionFactory sf = getCfg().buildSessionFactory();
	stats = sf.getStatistics();
	stats.clear();
	stats.setStatisticsEnabled(true);
	s = sf.openSession();
	tx = s.beginTransaction();
	europe = fillDb(s);
	tx.commit();
	s.clear();
	tx = s.beginTransaction();
	assertEquals( 0, stats.getCollectionLoadCount() );
	assertEquals( 0, stats.getCollectionFetchCount() );
	europe2 = (Continent) s.get( Continent.class, europe.getId() );
	assertEquals( 1, stats.getCollectionLoadCount() );
	assertEquals( "Should do direct load, not indirect second load when lazy false and JOIN", 0, stats.getCollectionFetchCount() );
	tx.commit();
	s.close();
	sf.close();

	coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
	coll.setFetchMode(FetchMode.SELECT);
	coll.setLazy(false);
	sf = getCfg().buildSessionFactory();
	stats = sf.getStatistics();
	stats.clear();
	stats.setStatisticsEnabled(true);
	s = sf.openSession();
	tx = s.beginTransaction();
	europe = fillDb(s);
	tx.commit();
	s.clear();
	tx = s.beginTransaction();
	assertEquals( 0, stats.getCollectionLoadCount() );
	assertEquals( 0, stats.getCollectionFetchCount() );
	europe2 = (Continent) s.get( Continent.class, europe.getId() );
	assertEquals( 1, stats.getCollectionLoadCount() );
	assertEquals( "Should do explicit collection load, not part of the first one", 1, stats.getCollectionFetchCount() );
	Iterator countries = europe2.getCountries().iterator();
	while ( countries.hasNext() ) {
		s.delete( countries.next() );
	}
	cleanDb( s );
	tx.commit();
	s.close();
}
 
Example 20
Source File: OrderByTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testOrderBy() {
	Search s = new Search("Hibernate");
	s.getSearchResults().add("jboss.com");
	s.getSearchResults().add("hibernate.org");
	s.getSearchResults().add("HiA");
	
	Session sess = openSession();
	Transaction tx = sess.beginTransaction();
	sess.persist(s);
	sess.flush();
	
	sess.clear();
	s = (Search) sess.createCriteria(Search.class).uniqueResult();
	assertFalse( Hibernate.isInitialized( s.getSearchResults() ) );
	Iterator iter = s.getSearchResults().iterator();
	assertEquals( iter.next(), "HiA" );
	assertEquals( iter.next(), "hibernate.org" );
	assertEquals( iter.next(), "jboss.com" );
	assertFalse( iter.hasNext() );
	
	sess.clear();
	s = (Search) sess.createCriteria(Search.class)
			.setFetchMode("searchResults", FetchMode.JOIN)
			.uniqueResult();
	assertTrue( Hibernate.isInitialized( s.getSearchResults() ) );
	iter = s.getSearchResults().iterator();
	assertEquals( iter.next(), "HiA" );
	assertEquals( iter.next(), "hibernate.org" );
	assertEquals( iter.next(), "jboss.com" );
	assertFalse( iter.hasNext() );
	
	sess.clear();
	s = (Search) sess.createQuery("from Search s left join fetch s.searchResults")
			.uniqueResult();
	assertTrue( Hibernate.isInitialized( s.getSearchResults() ) );
	iter = s.getSearchResults().iterator();
	assertEquals( iter.next(), "HiA" );
	assertEquals( iter.next(), "hibernate.org" );
	assertEquals( iter.next(), "jboss.com" );
	assertFalse( iter.hasNext() );
	
	/*sess.clear();
	s = (Search) sess.createCriteria(Search.class).uniqueResult();
	assertFalse( Hibernate.isInitialized( s.getSearchResults() ) );
	iter = sess.createFilter( s.getSearchResults(), "").iterate();
	assertEquals( iter.next(), "HiA" );
	assertEquals( iter.next(), "hibernate.org" );
	assertEquals( iter.next(), "jboss.com" );
	assertFalse( iter.hasNext() );*/
	
	sess.delete(s);
	tx.commit();
	sess.close();
}