org.hibernate.Session#delete ( )源码实例Demo

下面列出了org.hibernate.Session#delete ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * 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);
		}
	}
}
 
源代码2 项目: unitime   文件: StudentGroups.java
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);
}
 
源代码3 项目: cacheonix-core   文件: ASTParserLoadingTest.java
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();
}
 
源代码4 项目: Knowage-Server   文件: SbiGeoMapsDAOHibImpl.java
/**
 * 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();
		}

	}
}
 
源代码5 项目: cacheonix-core   文件: SequenceIdentityTest.java
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();
}
 
源代码6 项目: document-management-system   文件: ForumDAO.java
/**
 * 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);
	}
}
 
源代码7 项目: redisson   文件: TransactionalTest.java
@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();
    
}
 
源代码8 项目: Knowage-Server   文件: ConfigDAOHibImpl.java
/**
 * 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");
}
 
源代码9 项目: fastdfs-zyc   文件: WarningServiceImpl.java
@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);
}
 
源代码10 项目: spacewalk   文件: HibernateFactory.java
/**
 * 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;
}
 
源代码11 项目: redisson   文件: TransactionalTest.java
@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();
}
 
源代码12 项目: uyuni   文件: ErrataFactory.java
/**
 * 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;
}
 
源代码13 项目: unitime   文件: OfferingConsentTypes.java
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);
}
 
源代码14 项目: Knowage-Server   文件: MetaModelParuseDAOHibImpl.java
@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();
		}
	}
}
 
源代码15 项目: cacheonix-core   文件: PropertyRefTest.java
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();
}
 
源代码16 项目: Knowage-Server   文件: DataSourceDAOHibImpl.java
/**
 * 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");
		}
	}

}
 
源代码17 项目: Knowage-Server   文件: SbiNewsDAOImpl.java
@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");

}
 
源代码18 项目: Knowage-Server   文件: MenuDAOImpl.java
/**
 * 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();
		}
	}

}
 
源代码19 项目: cacheonix-core   文件: CollectionTest.java
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();

}
 
源代码20 项目: cacheonix-core   文件: StatsTest.java
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();
}