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

The following examples show how to use org.hibernate.Session#evict() . 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: BaseHibernateManager.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected void updateAssignment(final GradebookAssignment assignment) throws ConflictingAssignmentNameException, HibernateException {
	// Ensure that we don't have the assignment in the session, since
	// we need to compare the existing one in the db to our edited assignment
       final Session session = getSessionFactory().getCurrentSession();
	session.evict(assignment);

	final GradebookAssignment asnFromDb = (GradebookAssignment) session.load(GradebookAssignment.class, assignment.getId());

	final Long count = (Long) session.createCriteria(GradableObject.class)
               .add(Restrictions.eq("name", assignment.getName()))
               .add(Restrictions.eq("gradebook", assignment.getGradebook()))
               .add(Restrictions.ne("id", assignment.getId()))
               .add(Restrictions.eq("removed", false))
               .setProjection(Projections.rowCount())
               .uniqueResult();
	if(count > 0) {
		throw new ConflictingAssignmentNameException("You can not save multiple assignments in a gradebook with the same name");
	}

	session.evict(asnFromDb);
	session.update(assignment);
}
 
Example 2
Source File: HostBuilder.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This is the final step in building or compiling a host. The host and its guests (if
 * there are any) will be persisted, flushed, and evicted from the current hibernate
 * session.
 * <p>
 * The builder does not maintain a reference to a host once it is built; so, calling
 * <code>build</code> successive times will simply return <code>null</code>. One of the
 * <i>create</i> methods must be called before every invocation of this method.
 *
 * @return The built host whose state will have persisted and synhronized with the
 * database. The host and its guests will have been removed from the hibernate session
 * cache.
 */
public Server build() {
   if (host == null) {
       return null;
   }

   Server compiledHost;
   Session session = HibernateFactory.getSession();

   session.flush();
   session.evict(host);

   for (Iterator iterator = host.getGuests().iterator(); iterator.hasNext();) {
       session.evict(iterator.next());
   }

   compiledHost = host;
   host = null;

   return compiledHost;
}
 
Example 3
Source File: HostBuilder.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This is the final step in building or compiling a host. The host and its guests (if
 * there are any) will be persisted, flushed, and evicted from the current hibernate
 * session.
 * <p>
 * The builder does not maintain a reference to a host once it is built; so, calling
 * <code>build</code> successive times will simply return <code>null</code>. One of the
 * <i>create</i> methods must be called before every invocation of this method.
 *
 * @return The built host whose state will have persisted and synhronized with the
 * database. The host and its guests will have been removed from the hibernate session
 * cache.
 */
public Server build() {
   if (host == null) {
       return null;
   }

   Server compiledHost;
   Session session = HibernateFactory.getSession();

   session.flush();
   session.evict(host);

   for (Iterator iterator = host.getGuests().iterator(); iterator.hasNext();) {
       session.evict(iterator.next());
   }

   compiledHost = host;
   host = null;

   return compiledHost;
}
 
Example 4
Source File: HibernateFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Util to reload an object using Hibernate
 * @param obj to be reloaded
 * @return Object found if not, null
 * @throws HibernateException if something bad happens.
 */
public static Object reload(Object obj) throws HibernateException {
    // assertNotNull(obj);
    ClassMetadata cmd = connectionManager.getMetadata(obj);
    Serializable id = cmd.getIdentifier(obj, (SessionImplementor) getSession());
    Session session = getSession();
    session.flush();
    session.evict(obj);
    /*
     * In hibernate 3, the following doesn't work:
     * session.load(obj.getClass(), id);
     * load returns the proxy class instead of the persisted class, ie,
     * Filter$$EnhancerByCGLIB$$9bcc734d_2 instead of Filter.
     * session.get is set to not return the proxy class, so that is what we'll use.
     */
    // assertNotSame(obj, result);
    return session.get(obj.getClass(), id);
}
 
Example 5
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void update(E e) {
	try {
		Session session = getCurrentSession();
		session.saveOrUpdate(e);
		session.flush();
		session.evict(e);
	} catch (Exception ex) {
		logger.error("Update failed", ex);
		throw new HibernateException("Update failed");
	}
}
 
Example 6
Source File: ConfigurationFactoryTest.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
public void testRemoveConfigChannel() {

        //Let's create a channel/file/revision
        ConfigRevision cr = ConfigTestUtils.createConfigRevision(user.getOrg());
        ConfigChannel channel = cr.getConfigFile().getConfigChannel();
        assertNotNull(cr.getId());

        //now let's create another file in this channel without a revision,
        //just to test things out.
        ConfigFile file = ConfigTestUtils.createConfigFile(channel);
        assertNotNull(file.getId());

        //We have to evict everything from the session so that hibernate
        //doesn't complain that we removed things out from under its feet.
        Session session = HibernateFactory.getSession();
        session.flush();
        session.evict(channel);
        session.evict(file);
        session.evict(cr.getConfigFile());
        session.evict(cr);

        //run the method we are testing
        ConfigurationFactory.removeConfigChannel(channel);

        //confirm that the channel is gone.
        assertNull(ConfigurationFactory.lookupConfigChannelById(channel.getId()));
        //and everything that was in the channel.
        assertNull(ConfigurationFactory.lookupConfigFileById(file.getId()));
        assertNull(ConfigurationFactory.lookupConfigFileById(cr.getConfigFile().getId()));
        assertNull(ConfigurationFactory.lookupConfigRevisionById(cr.getId()));
    }
 
Example 7
Source File: MenuDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void updateMenu(SbiMenu hibMenu) throws EMFUserError {
	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();
		this.updateSbiCommonInfo4Update(hibMenu);
		tmpSession.evict(hibMenu);
		tmpSession.update(hibMenu);

		tx.commit();
	} catch (HibernateException he) {
		logException(he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {

		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}

	}
}
 
Example 8
Source File: ConfigurationFactoryTest.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
public void testRemoveConfigChannel() {

        //Let's create a channel/file/revision
        ConfigRevision cr = ConfigTestUtils.createConfigRevision(user.getOrg());
        ConfigChannel channel = cr.getConfigFile().getConfigChannel();
        assertNotNull(cr.getId());

        //now let's create another file in this channel without a revision,
        //just to test things out.
        ConfigFile file = ConfigTestUtils.createConfigFile(channel);
        assertNotNull(file.getId());

        //We have to evict everything from the session so that hibernate
        //doesn't complain that we removed things out from under its feet.
        Session session = HibernateFactory.getSession();
        session.flush();
        session.evict(channel);
        session.evict(file);
        session.evict(cr.getConfigFile());
        session.evict(cr);

        //run the method we are testing
        ConfigurationFactory.removeConfigChannel(channel);

        //confirm that the channel is gone.
        assertNull(ConfigurationFactory.lookupConfigChannelById(channel.getId()));
        //and everything that was in the channel.
        assertNull(ConfigurationFactory.lookupConfigFileById(file.getId()));
        assertNull(ConfigurationFactory.lookupConfigFileById(cr.getConfigFile().getId()));
        assertNull(ConfigurationFactory.lookupConfigRevisionById(cr.getId()));
    }
 
Example 9
Source File: HibernateEHCacheMain.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	
	System.out.println("Temp Dir:"+System.getProperty("java.io.tmpdir"));
	
	//Initialize Sessions
	SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
	Statistics stats = sessionFactory.getStatistics();
	System.out.println("Stats enabled="+stats.isStatisticsEnabled());
	stats.setStatisticsEnabled(true);
	System.out.println("Stats enabled="+stats.isStatisticsEnabled());
	
	Session session = sessionFactory.openSession();
	Session otherSession = sessionFactory.openSession();
	Transaction transaction = session.beginTransaction();
	Transaction otherTransaction = otherSession.beginTransaction();
	
	printStats(stats, 0);
	
	Employee emp = (Employee) session.load(Employee.class, 1L);
	printData(emp, stats, 1);
	
	emp = (Employee) session.load(Employee.class, 1L);
	printData(emp, stats, 2);
	
	//clear first level cache, so that second level cache is used
	session.evict(emp);
	emp = (Employee) session.load(Employee.class, 1L);
	printData(emp, stats, 3);
	
	emp = (Employee) session.load(Employee.class, 3L);
	printData(emp, stats, 4);
	
	emp = (Employee) otherSession.load(Employee.class, 1L);
	printData(emp, stats, 5);
	
	//Release resources
	transaction.commit();
	otherTransaction.commit();
	sessionFactory.close();
}
 
Example 10
Source File: JpaBaseRepository.java    From jadira with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public T evict(T entity) {

	Session session = (Session) getEntityManager().getDelegate();
	session.evict(entity);

	return entity;
}
 
Example 11
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void delete(E e) {
	try {
		Session session = getCurrentSession();
		session.buildLockRequest(LockOptions.UPGRADE).lock(e);
		session.delete(e);
		session.flush();
		session.evict(e);
	} catch (Exception ex) {
		logger.error("Delete failed", ex);
		throw new HibernateException("Delete failed");
	}
}
 
Example 12
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Object merge(E e) {
	try {
		Session session = getCurrentSession();
		Object o = (Object) session.merge(e);
		session.flush();
		session.evict(e);
		return o;
	} catch (Exception ex) {
		logger.error("Merge failed", ex);
		throw new HibernateException("Merge failed");
	}

}
 
Example 13
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 14
Source File: TestUtils.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Util to flush and evict an object from the Hibernate Session
 * @param obj to flush
 * @throws HibernateException if something bad happens
 */
public static void flushAndEvict(Object obj) throws HibernateException {
    Session session = HibernateFactory.getSession();
    session.flush();
    session.evict(obj);
}
 
Example 15
Source File: AlarmDefinitionSqlImpl.java    From monasca-thresh with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public List<AlarmDefinition> listAll() {

  Session session = null;
  List<AlarmDefinition> alarmDefinitions = null;

  try {
    session = sessionFactory.openSession();
    List<AlarmDefinitionDb> alarmDefDbList = session
        .createCriteria(AlarmDefinitionDb.class)
        .add(Restrictions.isNull("deletedAt"))
        .addOrder(Order.asc("createdAt"))
        .setReadOnly(true)
        .list();

    if (alarmDefDbList != null) {
      alarmDefinitions = Lists.newArrayListWithExpectedSize(alarmDefDbList.size());

      for (final AlarmDefinitionDb alarmDefDb : alarmDefDbList) {
        final Collection<String> matchBy = alarmDefDb.getMatchByAsCollection();
        final boolean actionEnable = alarmDefDb.isActionsEnabled();

        alarmDefinitions.add(new AlarmDefinition(
            alarmDefDb.getId(),
            alarmDefDb.getTenantId(),
            alarmDefDb.getName(),
            alarmDefDb.getDescription(),
            AlarmExpression.of(alarmDefDb.getExpression()),
            alarmDefDb.getSeverity().name(),
            actionEnable,
            this.findSubExpressions(session, alarmDefDb.getId()),
            matchBy.isEmpty() ? Collections.<String>emptyList() : Lists.newArrayList(matchBy)
        ));

        session.evict(alarmDefDb);
      }

    }

    return alarmDefinitions == null ? Collections.<AlarmDefinition>emptyList() : alarmDefinitions;
  } finally {
    if (session != null) {
      session.close();
    }
  }
}
 
Example 16
Source File: CacheHandlerTest.java    From pnc with Apache License 2.0 4 votes vote down vote up
@Test
public void testFirstLevelCacheEviction() {

    // Session 3
    em_3 = getEmFactory().createEntityManager();
    Session session_3 = (Session) em_3.getDelegate();
    SessionFactory sessionFactory_3 = session_3.getSessionFactory();

    // Initialize sample build configurations, these cannot be done by DBUnit because of the Hibernate Envers
    // Auditing
    insertExampleBuildConfigurations(em_1, basicRepositoryConfiguration);

    BuildConfiguration buildConfig3 = BuildConfiguration.Builder.newBuilder()
            .id(3)
            .name("Test Build Configuration 3")
            .description("Test Build Configuration 3 Description")
            .project(Project.Builder.newBuilder().id(1).build())
            .repositoryConfiguration(basicRepositoryConfiguration)
            .buildScript("mvn install")
            .buildEnvironment(BuildEnvironment.Builder.newBuilder().id(1).build())
            .build();

    // Persist in Session 1
    em_1.getTransaction().begin();
    em_1.persist(buildConfig3);
    em_1.getTransaction().commit();

    Integer newBCId = buildConfig3.getId();

    // Entity is fetched very first time
    BuildConfiguration bc = (BuildConfiguration) session_3.load(BuildConfiguration.class, newBCId);

    SortedMap<String, HibernateMetric> genericStats = getGenericStats(sessionFactory_3.getStatistics());
    double entityFetchCount1 = Double
            .parseDouble(genericStats.get("hibernate-orm.entities.fetch.count").getValue());
    double secondLevelCacheHitCount1 = Double
            .parseDouble(genericStats.get("hibernate-orm.second-level-cache.hit.count").getValue());

    // fetch the BuildConfiguration entity again, no change in fetch count from 1st level cache nor access to 2nd
    // level
    // cache as there is no need for it
    bc = (BuildConfiguration) session_3.load(BuildConfiguration.class, newBCId);

    SortedMap<String, HibernateMetric> genericStats_2 = getGenericStats(sessionFactory_3.getStatistics());
    double entityFetchCount2 = Double
            .parseDouble(genericStats_2.get("hibernate-orm.entities.fetch.count").getValue());
    double secondLevelCacheHitCount2 = Double
            .parseDouble(genericStats_2.get("hibernate-orm.second-level-cache.hit.count").getValue());

    // No change in fetch from 1st and 2nd level caches
    assertEquals((int) entityFetchCount1, (int) entityFetchCount2);
    assertEquals((int) secondLevelCacheHitCount2, (int) secondLevelCacheHitCount2);

    // Evict from first level cache
    session_3.evict(bc);

    // fetch one more time
    bc = (BuildConfiguration) session_3.load(BuildConfiguration.class, newBCId);

    SortedMap<String, HibernateMetric> genericStats_3 = getGenericStats(sessionFactory_3.getStatistics());
    double entityFetchCount3 = Double
            .parseDouble(genericStats_3.get("hibernate-orm.entities.fetch.count").getValue());
    double secondLevelCacheHitCount3 = Double
            .parseDouble(genericStats_3.get("hibernate-orm.second-level-cache.hit.count").getValue());

    // No change in fetch from 1st level cache as entity is not there anymore
    assertEquals((int) entityFetchCount2, (int) entityFetchCount3);
    // Change in fetch from 2nd level cache: the entity is not in 1st level cache anymore, so Hibernate gets it from
    // 2nd
    // level
    assertNotEquals(secondLevelCacheHitCount2, secondLevelCacheHitCount3);

    logger.debug(
            "Entity fetch count #1: {}, #2: {}, #3: {}",
            entityFetchCount1,
            entityFetchCount2,
            entityFetchCount3);
    logger.debug(
            "Second level cache hit count #1: {}, #2: {}, #3: {}",
            secondLevelCacheHitCount1,
            secondLevelCacheHitCount2,
            secondLevelCacheHitCount3);
}
 
Example 17
Source File: SaveOrUpdateTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testEvictThenSaveOrUpdate() {
	Session s = openSession();
	s.getTransaction().begin();
	Node parent = new Node( "1:parent" );
	Node child = new Node( "2:child" );
	Node grandchild = new Node( "3:grandchild" );
	parent.addChild( child );
	child.addChild( grandchild );
	s.saveOrUpdate( parent );
	s.getTransaction().commit();
	s.close();

	Session s1 = openSession();
	s1.getTransaction().begin();
	child = ( Node ) s1.load( Node.class, "2:child" );
	assertTrue( s1.contains( child ) );
	assertFalse( Hibernate.isInitialized( child ) );
	assertTrue( s1.contains( child.getParent() ) );
	assertTrue( Hibernate.isInitialized( child ) );
	assertFalse( Hibernate.isInitialized( child.getChildren() ) );
	assertFalse( Hibernate.isInitialized( child.getParent() ) );
	assertTrue( s1.contains( child ) );
	s1.evict( child );
	assertFalse( s1.contains( child ) );
	assertTrue( s1.contains( child.getParent() ) );

	Session s2 = openSession();
	s2.getTransaction().begin();
	s2.saveOrUpdate( child );
	assertTrue( s2.contains( child ) );
	assertFalse( s1.contains( child ) );
	assertTrue( s2.contains( child.getParent() ) );
	assertFalse( s1.contains( child.getParent() ) );
	assertFalse( Hibernate.isInitialized( child.getChildren() ) );
	assertFalse( Hibernate.isInitialized( child.getParent() ) );
	assertEquals( 1, child.getChildren().size() );
	assertEquals( "1:parent", child.getParent().getName() );
	assertTrue( Hibernate.isInitialized( child.getChildren() ) );
	assertFalse( Hibernate.isInitialized( child.getParent() ) );
	assertNull( child.getParent().getDescription() );
	assertTrue( Hibernate.isInitialized( child.getParent() ) );

	s1.getTransaction().commit();
	s2.getTransaction().commit();
	s1.close();
	s2.close();

	s = openSession();
	s.beginTransaction();
	s.delete( s.get( Node.class, "3:grandchild" ) );
	s.delete( s.get( Node.class, "2:child" ) );
	s.delete( s.get( Node.class, "1:parent" ) );
	s.getTransaction().commit();
	s.close();
}
 
Example 18
Source File: RhnBaseTestCase.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
protected void flushAndEvict(Object obj) throws HibernateException {
    Session session = HibernateFactory.getSession();
    session.flush();
    session.evict(obj);
}
 
Example 19
Source File: RhnBaseTestCase.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
protected void flushAndEvict(Object obj) throws HibernateException {
    Session session = HibernateFactory.getSession();
    session.flush();
    session.evict(obj);
}
 
Example 20
Source File: TestUtils.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Util to flush and evict an object from the Hibernate Session
 * @param obj to flush
 * @throws HibernateException if something bad happens
 */
public static void flushAndEvict(Object obj) throws HibernateException {
    Session session = HibernateFactory.getSession();
    session.flush();
    session.evict(obj);
}