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

The following examples show how to use org.hibernate.Session#delete() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Purge in depth helper
 */
@SuppressWarnings("unchecked")
public void purgeHelper(Session session, String parentUuid) throws HibernateException, IOException {
	String qs = "from NodeDocumentVersion ndv where ndv.parent=:parent";
	Query q = session.createQuery(qs);
	q.setString("parent", parentUuid);
	List<NodeDocumentVersion> listDocVersions = q.list();

	for (NodeDocumentVersion nDocVer : listDocVersions) {
		String author = nDocVer.getAuthor();
		long size = nDocVer.getSize();

		if (FsDataStore.DATASTORE_BACKEND_FS.equals(Config.REPOSITORY_DATASTORE_BACKEND)) {
			FsDataStore.delete(nDocVer.getUuid());
		}

		session.delete(nDocVer);

		// Update user items size
		if (Config.USER_ITEM_CACHE) {
			UserItemsManager.decSize(author, size);
		}
	}
}
 
Example 2
Source Project: unitime   File: StudentGroups.java    License: Apache License 2.0 6 votes vote down vote up
protected void delete(StudentGroup group, SessionContext context, Session hibSession, Set<Long> studentIds) {
	if (group == null) return;
	if (group.getStudents() != null)
		for (Student student: group.getStudents()) {
			studentIds.add(student.getUniqueId());
			student.getGroups().remove(group);
		}
	ChangeLog.addChange(hibSession,
			context,
			group,
			group.getGroupAbbreviation() + " " + group.getGroupName(),
			Source.SIMPLE_EDIT, 
			Operation.DELETE,
			null,
			null);
	hibSession.delete(group);
}
 
Example 3
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 4
/**
 * Erase map.
 *
 * @param aMap
 *            the a map
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.geo.bo.dao.IEngineDAO#eraseEngine(it.eng.spagobi.bo.Engine)
 */
@Override
public void eraseMap(GeoMap aMap) throws EMFUserError {

	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		SbiGeoMaps hibMap = (SbiGeoMaps) tmpSession.load(SbiGeoMaps.class, new Integer(aMap.getMapId()));

		tmpSession.delete(hibMap);

		// delete template from sbi_binary_contents
		SbiBinContents hibBinCont = hibMap.getBinContents();
		if (hibBinCont != null)
			tmpSession.delete(hibBinCont);

		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 5
public void testSequenceIdentityGenerator() {
	Session session = openSession();
	session.beginTransaction();

	MyEntity e = new MyEntity( "entity-1" );
	session.save( e );

	// this insert should happen immediately!
	assertEquals( "id not generated through forced insertion", new Long(1), e.getId() );

	session.delete( e );
	session.getTransaction().commit();
	session.close();
}
 
Example 6
/**
 * Remove forum topics by parent node 
 */
@SuppressWarnings("unchecked")
public static void purgeTopicsByNode(String nodeUuid) throws DatabaseException {
	log.debug("purgeTopicsByNode({})", nodeUuid);
	String qs = "from ForumTopic ft where ft.node=:uuid";
	Session session = null;
	Transaction tx = null;

	try {
		session = HibernateUtil.getSessionFactory().openSession();
		tx = session.beginTransaction();

		Query q = session.createQuery(qs);
		q.setString("uuid", nodeUuid);

		for (ForumTopic ft : (List<ForumTopic>) q.list()) {
			session.delete(ft);
		}

		HibernateUtil.commit(tx);
		log.debug("purgeTopicsByNode: void");
	} catch (HibernateException e) {
		HibernateUtil.rollback(tx);
		throw new DatabaseException(e.getMessage(), e);
	} finally {
		HibernateUtil.close(session);
	}
}
 
Example 7
Source Project: redisson   File: TransactionalTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testQuery() {
    Statistics stats = sessionFactory().getStatistics();

    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional("data");
    item.getEntries().addAll(Arrays.asList("a", "b", "c"));
    s.save(item);
    s.flush();
    s.getTransaction().commit();
    
    s = openSession();
    s.beginTransaction();
    Query query = s.getNamedQuery("testQuery");
    query.setCacheable(true);
    query.setCacheRegion("myTestQuery");
    query.setParameter("name", "data");
    item = (ItemTransactional) query.uniqueResult();
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getPutCount());

    s = openSession();
    s.beginTransaction();
    Query query2 = s.getNamedQuery("testQuery");
    query2.setCacheable(true);
    query2.setCacheRegion("myTestQuery");
    query2.setParameter("name", "data");
    item = (ItemTransactional) query2.uniqueResult();
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getHitCount());
    
    stats.logSummary();
    
}
 
Example 8
/**
 * Delete config by id.
 *
 * @param id the id
 *
 * @return void
 *
 * @throws EMFUserError the EMF user error
 *
 */
@Override
public void delete(Integer idConfig) throws EMFUserError {
	logger.debug("IN");
	Session sess = null;
	Transaction tx = null;

	try {
		sess = getSession();
		tx = sess.beginTransaction();

		Criterion aCriterion = Expression.eq("id", idConfig);
		Criteria criteria = sess.createCriteria(SbiConfig.class);
		criteria.add(aCriterion);
		SbiConfig aSbiConfig = (SbiConfig) criteria.uniqueResult();
		if (aSbiConfig != null)
			sess.delete(aSbiConfig);
		tx.commit();

	} catch (HibernateException he) {
		logger.error("HibernateException", he);

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

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {
		if (sess != null) {
			if (sess.isOpen())
				sess.close();
		}
	}
	logger.debug("OUT");
}
 
Example 9
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void delWarUser(String id) throws IOException, MyException {
    //To change body of implemented methods use File | Settings | File Templates.
    WarningUser wu=new WarningUser();
    wu.setId(id);
    Session session = getSession();
    session.delete(wu);
}
 
Example 10
/**
 * Remove a Session from the DB
 * @param toRemove Object to be removed.
 * @return int number of objects affected.
 */
protected int removeObject(Object toRemove) {
    Session session = null;
    int numDeleted = 0;
    session = HibernateFactory.getSession();

    session.delete(toRemove);
    numDeleted++;

    return numDeleted;
}
 
Example 11
Source Project: redisson   File: TransactionalTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNaturalId() {
    Statistics stats = sessionFactory().getStatistics();
    Session s = openSession();
    s.beginTransaction();
    ItemTransactional item = new ItemTransactional("data");
    item.setNid("123");
    s.save(item);
    s.flush();
    s.getTransaction().commit();

    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
    Assert.assertEquals(1, stats.getNaturalIdCacheStatistics("item##NaturalId").getPutCount());
    
    s = openSession();
    s.beginTransaction();
    item = (ItemTransactional) s.bySimpleNaturalId(ItemTransactional.class).load("123");
    assertThat(item).isNotNull();
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
    Assert.assertEquals(1, stats.getNaturalIdCacheStatistics("item##NaturalId").getHitCount());

    sessionFactory().getStatistics().logSummary();
}
 
Example 12
/**
 * publish takes an unpublished errata and copies its contents into a Published Errata
 * object (and then returns this object). This method also handles removing the old
 * Unpublished Errata object and child elements from the db.
 * @param unpublished The Errata to publish
 * @return Returns a published errata.
 */
public static Errata publish(Errata unpublished) {
    //Make sure the errata we're publishing is unpublished
    if (unpublished.isPublished()) {
        return unpublished; //there is nothing we can do here
    }
    //Create a published errata using unpublished

    Errata published;

    if (unpublished.isCloned()) {
        published = new PublishedClonedErrata();
        ((PublishedClonedErrata)published).setOriginal(
                ((UnpublishedClonedErrata)unpublished).getOriginal());
    }
    else {
        published = ErrataFactory.createPublishedErrata();
    }

    copyDetails(published, unpublished, false);

    //Save the published Errata
    save(published);

    //Remove the unpublished Errata from db
    try {
        Session session = HibernateFactory.getSession();
        session.delete(unpublished);
    }
    catch (HibernateException e) {
        throw new HibernateRuntimeException(
                "Errors occurred while publishing errata", e);
    }

    //return the published errata
    return published;
}
 
Example 13
Source Project: unitime   File: OfferingConsentTypes.java    License: Apache License 2.0 5 votes vote down vote up
protected void delete(OfferingConsentType consent, SessionContext context, Session hibSession) {
	if (consent == null) return;
	ChangeLog.addChange(hibSession,
			context,
			consent,
			consent.getReference() + " " + consent.getLabel(),
			Source.SIMPLE_EDIT, 
			Operation.DELETE,
			null,
			null);
	hibSession.delete(consent);
}
 
Example 14
@Override
public void eraseMetaModelParuse(MetaModelParuse aMetaModelParuse) throws HibernateException {
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		String hql = "from SbiMetamodelParuse s where s.id = ? ";
		Query hqlQuery = aSession.createQuery(hql);
		hqlQuery.setInteger(0, aMetaModelParuse.getId().intValue());

		SbiMetamodelParuse sbiMetamodelParuse = (SbiMetamodelParuse) hqlQuery.uniqueResult();
		if (sbiMetamodelParuse == null) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), "eraseMetaModelParuse",
					"the MetaModelParuse with " + "id=" + aMetaModelParuse.getId() + " does not exist.");
		}
		aSession.delete(sbiMetamodelParuse);
		tx.commit();
	} catch (HibernateException he) {
		logException(he);
		if (tx != null)
			tx.rollback();
		throw new HibernateException(he.getLocalizedMessage(), he);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
}
 
Example 15
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 16
/**
 * Erase data source.
 *
 * @param aDataSource
 *            the a data source
 * @throws EMFUserError
 *             the EMF user error
 * @see it.eng.spagobi.tools.datasource.dao.IDataSourceDAO#eraseDataSource(it.eng.spagobi.tools.datasource.bo.DataSource)
 */
@Override
public void eraseDataSource(IDataSource aDataSource) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		// delete first all associations with tenants
		Query hibQuery2 = aSession.createQuery("from SbiOrganizationDatasource ds where ds.id.datasourceId = :dsId");
		hibQuery2.setInteger("dsId", aDataSource.getDsId());
		ArrayList<SbiOrganizationDatasource> dsOrganizations = (ArrayList<SbiOrganizationDatasource>) hibQuery2.list();
		for (Iterator iterator = dsOrganizations.iterator(); iterator.hasNext();) {
			SbiOrganizationDatasource sbiOrganizationDatasource = (SbiOrganizationDatasource) iterator.next();
			aSession.delete(sbiOrganizationDatasource);
			aSession.flush();
		}

		SbiDataSource hibDataSource = (SbiDataSource) aSession.load(SbiDataSource.class, new Integer(aDataSource.getDsId()));
		aSession.delete(hibDataSource);
		tx.commit();
	} catch (HibernateException he) {
		logger.error("Error while erasing the data source with id " + ((aDataSource == null) ? "" : String.valueOf(aDataSource.getDsId())), he);

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

		throw new EMFUserError(EMFErrorSeverity.ERROR, 8007);

	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
			logger.debug("OUT");
		}
	}

}
 
Example 17
@Override
public void deleteNews(Integer newsId, UserProfile profile) {

	logger.debug("IN");
	Transaction transaction = null;
	Session session = null;
	SbiNews newsForDelete;

	try {

		session = getSession();
		transaction = session.beginTransaction();

		String hql = "from SbiNews s where s.id = :newId";
		Query query = session.createQuery(hql);
		query.setInteger("newId", newsId);
		newsForDelete = (SbiNews) query.uniqueResult();

		if (UserUtilities.isTechnicalUser(profile) || getAvailableNews(newsForDelete, profile) != null) {

			session.delete(newsForDelete);

		} else {
			throw new SpagoBIRuntimeException("You are not allowed to get this news");
		}

		transaction.commit();

	} catch (HibernateException e) {
		logException(e);
		logger.error("Error in deleting news", e);
		if (transaction != null)
			transaction.rollback();

		throw new SpagoBIRuntimeException("Error occured while deleting news", e);

	} finally {

		if (session != null && session.isOpen())
			session.close();
	}

	logger.debug("OUT");

}
 
Example 18
/**
 * Modify menu.
 *
 * @param aMenu the a menu
 *
 * @throws EMFUserError the EMF user error
 *
 * @see it.eng.spagobi.wapp.dao.IMenuDAO#modifyMenu(it.eng.spagobi.wapp.bo.Menu)
 */
@SuppressWarnings("unchecked")
@Override
public void modifyMenu(Menu aMenu) throws EMFUserError {

	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		SbiMenu hibMenu = (SbiMenu) tmpSession.load(SbiMenu.class, aMenu.getMenuId());
		hibMenu.setName(aMenu.getName());
		hibMenu.setDescr(aMenu.getDescr());
		hibMenu.setParentId(aMenu.getParentId());
		hibMenu.setObjId(aMenu.getObjId());
		hibMenu.setObjParameters(aMenu.getObjParameters());
		hibMenu.setSubObjName(aMenu.getSubObjName());
		hibMenu.setSnapshotName(aMenu.getSnapshotName());
		hibMenu.setSnapshotHistory(aMenu.getSnapshotHistory());
		hibMenu.setFunctionality(aMenu.getFunctionality());
		hibMenu.setInitialPath(aMenu.getInitialPath());

		// Modify Roles Associated
		// delete all roles previously associated
		Set<SbiMenuRole> oldRoles = hibMenu.getSbiMenuRoles();
		Iterator<SbiMenuRole> iterOldRoles = oldRoles.iterator();
		while (iterOldRoles.hasNext()) {
			SbiMenuRole role = iterOldRoles.next();
			tmpSession.delete(role);
		}
		// save roles functionality
		Set<SbiMenuRole> menuRoleToSave = new HashSet<>();
		menuRoleToSave.addAll(saveRolesMenu(tmpSession, hibMenu, aMenu));
		// set new roles into sbiFunctions
		hibMenu.setSbiMenuRoles(menuRoleToSave);

		// delete incongruous roles associations
		deleteIncongruousRoles(tmpSession, hibMenu);

		hibMenu.setViewIcons(new Boolean(aMenu.isViewIcons()));
		hibMenu.setHideToolbar(new Boolean(aMenu.getHideToolbar()));
		hibMenu.setHideSliders(new Boolean(aMenu.getHideSliders()));

		hibMenu.setStaticPage(aMenu.getStaticPage());
		hibMenu.setExternalApplicationUrl(aMenu.getExternalApplicationUrl());

		if (aMenu.getIcon() == null) {
			hibMenu.setIcon(null);

		} else {
			hibMenu.setIcon(new Gson().toJson(aMenu.getIcon()).toString());
		}

		if (aMenu.getCustIcon() == null) {
			hibMenu.setCustIcon(null);
		} else {
			hibMenu.setCustIcon(new Gson().toJson(aMenu.getCustIcon()).toString());
		}
		updateSbiCommonInfo4Update(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 19
public void testUpdateOrder() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	User u = new User( "gavin" );
	u.getSessionData().put( "foo", "foo value" );
	u.getSessionData().put( "bar", "bar value" );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );
	s.persist( u );
	t.commit();
	s.close();

	u.getSessionData().clear();
	u.getSessionData().put( "baz", "baz value" );
	u.getSessionData().put( "bar", "bar value" );
	u.getEmailAddresses().remove( 0 );
	u.getEmailAddresses().remove( 2 );

	s = openSession();
	t = s.beginTransaction();
	s.update( u );
	t.commit();
	s.close();

	u.getSessionData().clear();
	u.getEmailAddresses().add( 0, new Email( "[email protected]" ) );
	u.getEmailAddresses().add( new Email( "[email protected]" ) );

	s = openSession();
	t = s.beginTransaction();
	s.update( u );
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	s.delete( u );
	t.commit();
	s.close();

}
 
Example 20
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();
}