org.hibernate.Transaction Java Examples

The following examples show how to use org.hibernate.Transaction. 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: LogCleaner.java    From unitime with Apache License 2.0 6 votes vote down vote up
public static void cleanupHashedQueries(int days) {
	if (days < 0) return;
	org.hibernate.Session hibSession = new _RootDAO().createNewSession();
	Transaction tx = null;
	try {
		tx = hibSession.beginTransaction();
		int rows = hibSession.createQuery(
				"delete from HashedQuery where lastUsed < " + HibernateUtil.addDate("current_date()", ":days")
				).setInteger("days", - days).executeUpdate();
		if (rows > 0)
			sLog.info("All records not used for more than " + days + " days deleted from the hashed queries (" + rows + " records).");
		tx.commit();
	} catch (Throwable t) {
		sLog.warn("Failed to cleanup student sectioning queue: " + t.getMessage(), t);
		if (tx != null) tx.rollback();
	} finally {
		hibSession.close();
	}
}
 
Example #2
Source File: DocumentExpirationServlet.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * clean
 */
private void clean(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DatabaseException,
		PrincipalAdapterException {
	log.debug("clean({}, {})", new Object[]{request, response});
	org.hibernate.Session dbSession = null;
	Transaction tx = null;

	try {
		dbSession = HibernateUtil.getSessionFactory().openSession();
		tx = dbSession.beginTransaction();
		String qs = "delete from DatabaseMetadataValue dmv where dmv.table='group'";
		Query q = dbSession.createQuery(qs);
		q.executeUpdate();
		HibernateUtil.commit(tx);
	} catch (HibernateException e) {
		HibernateUtil.rollback(tx);
		throw new DatabaseException(e.getMessage(), e);
	} finally {
		HibernateUtil.close(dbSession);
	}

	log.debug("clean: void");
}
 
Example #3
Source File: TenantsDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<Integer> loadSelectedProductTypesIds(String tenant) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		Query hibQuery = aSession
				.createQuery("select p.sbiProductType.productTypeId from SbiOrganizationProductType p where p.sbiOrganizations.name = :tenantName");
		hibQuery.setString("tenantName", tenant);
		ArrayList<Integer> result = (ArrayList<Integer>) hibQuery.list();
		return result;
	} catch (HibernateException he) {
		logger.error(he.getMessage(), he);
		if (tx != null)
			tx.rollback();
		throw new SpagoBIRuntimeException("Error getting Tenant Product Types", he);
	} finally {
		logger.debug("OUT");
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
}
 
Example #4
Source File: EventDAOimpl.java    From ALLGO with Apache License 2.0 6 votes vote down vote up
@Override
public boolean unfollow(int eid, int uid) {
	boolean flag = false ;
	try{
		EventFollowerVo pk = new EventFollowerVo();
		pk.setEid(eid);
		pk.setUid(uid);
		Session s = HibernateSessionFactory.getSession();
		Transaction t = s.beginTransaction();
		EventFollowerVo vo = (EventFollowerVo) s.load(EventFollowerVo.class, pk);
		s.delete(vo);
		t.commit();
		s.close();
		flag = true;
   }catch(Exception e){
	   	e.printStackTrace();
   }
	return flag;
}
 
Example #5
Source File: FumTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testListIdentifiers() throws Exception {
	Session s = openSession();
	Transaction txn = s.beginTransaction();
	Fum fum = new Fum( fumKey("fum") );
	fum.setFum("fo fee fi");
	s.save(fum);
	fum = new Fum( fumKey("fi") );
	fum.setFum("fee fi fo");
	s.save(fum);
	List list = s.find("select fum.id from Fum as fum where not fum.fum='FRIEND'");
	assertTrue( "list identifiers", list.size()==2);
	Iterator iter = s.iterate("select fum.id from Fum fum where not fum.fum='FRIEND'");
	int i=0;
	while ( iter.hasNext() ) {
		assertTrue( "iterate identifiers",  iter.next() instanceof FumCompositeID);
		i++;
	}
	assertTrue(i==2);

	s.delete( s.load(Fum.class, (Serializable) list.get(0) ) );
	s.delete( s.load(Fum.class, (Serializable) list.get(1) ) );
	txn.commit();
	s.close();
}
 
Example #6
Source File: DBQueryUtil.java    From kardio with Apache License 2.0 6 votes vote down vote up
/**
 * Get the current number of container from k8s_pods_containers
 * @param envId
 * @param platform
 * @return
 */
public static Map<String, Integer> getK8sCurrContainerDetails(int envId, String platform) {
	final java.sql.Date todayDate = new java.sql.Date(Calendar.getInstance().getTimeInMillis());;
	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	Criteria contCriteria = session.createCriteria(K8sPodsContainersEntity.class, "contSts");
	contCriteria.add(Restrictions.eq("contSts.statusDate", todayDate ));
	contCriteria.add(Restrictions.eq("contSts.environment.environmentId", envId));
	@SuppressWarnings("unchecked")
	List<K8sPodsContainersEntity> contEntityList = contCriteria.list();
	Map<String, Integer> mapContSts = new HashMap<String, Integer>();
	for(K8sPodsContainersEntity contStsEntity : contEntityList){
		if(contStsEntity.getComponent() != null && contStsEntity.getComponent().getParentComponent() != null){
			String fullAppName = contStsEntity.getComponent().getParentComponent().getComponentName() + "/" + contStsEntity.getComponent().getComponentName();
			mapContSts.put(fullAppName, contStsEntity.getTotalContainers());
	    }else if(contStsEntity.getComponent() != null){
	    	mapContSts.put(contStsEntity.getComponent().getComponentName(), contStsEntity.getTotalContainers());
	    }
    }
	txn.commit();
	return mapContSts;
}
 
Example #7
Source File: DBQueryUtil.java    From kardio with Apache License 2.0 6 votes vote down vote up
/**
 * Load the Pods&Containers of the objects other than Deployment
 * @param environmentId
 * @param objName
 * @param podContList
 */
public static void loadK8sObjectPods(int environmentId, String objName, ArrayList<Integer> podContList) {
	final java.sql.Date todayDate = new java.sql.Date(Calendar.getInstance().getTimeInMillis());;
	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	K8sObjectPodsEntity contStat = new K8sObjectPodsEntity();
	EnvironmentEntity environment = new EnvironmentEntity();
	environment.setEnvironmentId(environmentId);
	contStat.setEnvironment(environment);
	contStat.setStatusDate(todayDate);
	contStat.setObjectName(objName);
	contStat.setPods(podContList.get(0));
	contStat.setContainers(podContList.get(1));
	//contStat.setDeltaValue(deltaVal);
	session.save(contStat);
	txn.commit();
}
 
Example #8
Source File: SbiAttributeDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void deleteSbiAttributeById(Integer id) throws EMFUserError {
	logger.debug("IN");

	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		SbiAttribute attrToDelete = (SbiAttribute) aSession.load(SbiAttribute.class, id);
		aSession.delete(attrToDelete);
		tx.commit();
	} catch (HibernateException he) {
		logger.error(he.getMessage(), he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		logger.debug("OUT");
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}

}
 
Example #9
Source File: CacheHibernateBlobStoreSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
    super.afterTest();

    Session s = store.session(null);

    if (s == null)
        return;

    try {
        s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
                .setFlushMode(FlushMode.ALWAYS).executeUpdate();

        Transaction hTx = s.getTransaction();

        if (hTx != null && hTx.getStatus() == TransactionStatus.ACTIVE)
            hTx.commit();
    }
    finally {
        s.close();
    }
}
 
Example #10
Source File: AbstractTest.java    From hibernate-master-class with Apache License 2.0 6 votes vote down vote up
protected <T> T doInJDBC(ConnectionCallable<T> callable) {
    AtomicReference<T> result = new AtomicReference<>();
    Session session = null;
    Transaction txn = null;
    try {
        session = getSessionFactory().openSession();
        txn = session.beginTransaction();
        session.doWork(connection -> {
            result.set(callable.execute(connection));
        });
        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive() ) txn.rollback();
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return result.get();
}
 
Example #11
Source File: CacheHibernateBlobStoreSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
    super.afterTest();

    Session s = store.session(null);

    if (s == null)
        return;

    try {
        s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
                .setFlushMode(FlushMode.ALWAYS).executeUpdate();

        Transaction hTx = s.getTransaction();

        if (hTx != null && hTx.isActive())
            hTx.commit();
    }
    finally {
        s.close();
    }
}
 
Example #12
Source File: ComponentTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testNamedQuery() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	s.getNamedQuery("userNameIn")
		.setParameterList( "nameList", new Object[] {"1ovthafew", "turin", "xam"} )
		.list();
	t.commit();
	s.close();
}
 
Example #13
Source File: DatasetDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Dataset updateDatasetName(String datasetId, String datasetName)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    DatasetEntity datasetObj = session.load(DatasetEntity.class, datasetId);

    Dataset dataset =
        Dataset.newBuilder()
            .setName(datasetName)
            .setWorkspaceId(datasetObj.getWorkspace())
            .setWorkspaceTypeValue(datasetObj.getWorkspace_type())
            .build();
    // Check entity already exists
    checkDatasetAlreadyExist(dataset);

    datasetObj.setName(datasetName);
    datasetObj.setTime_updated(Calendar.getInstance().getTimeInMillis());
    Transaction transaction = session.beginTransaction();
    session.update(datasetObj);
    transaction.commit();
    LOGGER.debug(ModelDBMessages.DATASET_UPDATE_SUCCESSFULLY_MSG);
    return datasetObj.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return updateDatasetName(datasetId, datasetName);
    } else {
      throw ex;
    }
  }
}
 
Example #14
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 #15
Source File: HibernateUtil.java    From webdsl with Apache License 2.0 5 votes vote down vote up
public void beforeTransactionCompletion(Transaction tx) {
	try {
		beforeTransactionCompletion_.beforeTransactionCompletion_();
	}
	catch (Exception e) {
	  AbstractPageServlet ps = ThreadLocalPage.get();
	  if(ps != null){
		  ps.exceptionInHibernateInterceptor = e;
	  }
	}
}
 
Example #16
Source File: SbiGeoFeaturesDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load all features.
 * 
 * @return the list
 * 
 * @throws EMFUserError the EMF user error
 * 
 * @see it.eng.spagobi.geo.bo.dao.IEngineDAO#loadAllEngines()
 */
public List loadAllFeatures() throws EMFUserError {
	Session tmpSession = null;
	Transaction tx = null;
	List realResult = new ArrayList();
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		Query hibQuery = tmpSession.createQuery(" from SbiGeoFeatures");
		
		List hibList = hibQuery.list();
		Iterator it = hibList.iterator();			
		while (it.hasNext()) {			
			SbiGeoFeatures hibFeature = (SbiGeoFeatures) it.next();	
			if (hibFeature != null) {
				GeoFeature bifeature = hibFeature.toGeoFeature();	
				realResult.add(bifeature);
			}
		}

		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();
		}
		
	}
	return realResult;
}
 
Example #17
Source File: SbiUserDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load SbiUser by id.
 *
 * @param id the identifier /** Load SbiUser by id.
 * @param id the bi object id
 * @return the BI object
 * @throws SpagoBIDAOException
 */
@Override
public SbiUser loadSbiUserById(Integer id) {
	logger.debug("IN");
	SbiUser toReturn = null;
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		toReturn = (SbiUser) aSession.load(SbiUser.class, id);

		Hibernate.initialize(toReturn);
		Hibernate.initialize(toReturn.getSbiExtUserRoleses());
		Hibernate.initialize(toReturn.getSbiUserAttributeses());
		for (SbiUserAttributes current : toReturn.getSbiUserAttributeses()) {
			Hibernate.initialize(current.getSbiAttribute());
		}

		tx.commit();
	} catch (HibernateException he) {
		if (tx != null)
			tx.rollback();
		throw new SpagoBIDAOException("Error while loading user by id " + id, he);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
	logger.debug("OUT");
	return toReturn;
}
 
Example #18
Source File: ObjMetacontentDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Erase object's metadata content
 *
 * @param ObjMetacontent
 *            the metadata content
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.tools.objmetadata.dao.IObjMetadataDAO#eraseObjMetadata(it.eng.spagobi.tools.objmetadata.bo.ObjMetacontent)
 */
@Override
public void eraseObjMetadata(ObjMetacontent aObjMetacontent) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		SbiObjMetacontents hibContents = (SbiObjMetacontents) aSession.load(SbiObjMetacontents.class, new Integer(aObjMetacontent.getObjMetacontentId()));

		aSession.delete(hibContents);
		tx.commit();
	} catch (HibernateException he) {
		logger.error(
				"Error while erasing the data source with id " + ((aObjMetacontent == null) ? "" : String.valueOf(aObjMetacontent.getObjMetacontentId())),
				he);

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

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

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

}
 
Example #19
Source File: MenuDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void importMenu(SbiMenu hibMenu) throws EMFUserError {
	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();
		this.updateSbiCommonInfo4Update(hibMenu);
		tmpSession.save(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 #20
Source File: SbiGeoMapsDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load map by id.
 *
 * @param mapID
 *            the map id
 *
 * @return the geo map
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.mapcatalogue.dao.geo.bo.dao.ISbiGeoMapsDAO#loadMapByID(integer)
 */
@Override
public GeoMap loadMapByID(Integer mapID) throws EMFUserError {
	GeoMap toReturn = null;
	Session tmpSession = null;
	Transaction tx = null;

	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();
		SbiGeoMaps hibMap = (SbiGeoMaps) tmpSession.load(SbiGeoMaps.class, mapID);
		toReturn = hibMap.toGeoMap();
		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();

		}
	}
	return toReturn;
}
 
Example #21
Source File: ClientElbDAOTest.java    From flux with Apache License 2.0 5 votes vote down vote up
private void clean() throws Exception {
    Session session = sessionFactory.getSchedulerSessionFactory().openSession();
    ManagedSessionContext.bind(session);
    Transaction tx = session.beginTransaction();
    try {
        session.createSQLQuery("delete from ClientElb").executeUpdate();
        tx.commit();
    } finally {
        if (session != null) {
            ManagedSessionContext.unbind(session.getSessionFactory());
            session.close();
            sessionFactory.clear();
        }
    }
}
 
Example #22
Source File: SbiMetaTableDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<SbiMetaTable> loadTablesFromSource(int sourceId) throws EMFUserError {
	logger.debug("IN");

	List toReturn = null;
	Session tmpSession = null;
	Transaction tx = null;

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

		Criterion labelCriterrion = Expression.eq("sourceid", sourceId);
		Criteria criteria = tmpSession.createCriteria(SbiMetaTable.class);
		criteria.add(labelCriterrion);

		toReturn = criteria.list();
		if (toReturn == null)
			return null;
		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();
		}
	}

	logger.debug("OUT");
	return toReturn;
}
 
Example #23
Source File: ObjParuseDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load obj paruses.
 *
 * @param objParId the obj par id
 *
 * @return the list
 *
 * @throws EMFUserError the EMF user error
 *
 * @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IObjParuseDAO#loadObjParuses(Integer)
 */
@Override
public List loadObjParuses(Integer objParId) throws HibernateException {
	List toReturn = new ArrayList();
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		// String hql = "from SbiObjParuse s where s.id.sbiObjPar.objParId = " + objParId + " order by s.prog";
		String hql = "from SbiObjParuse s where s.sbiObjPar.objParId = ? order by s.prog";
		Query hqlQuery = aSession.createQuery(hql);
		hqlQuery.setInteger(0, objParId.intValue());
		List sbiObjParuses = hqlQuery.list();
		Iterator it = sbiObjParuses.iterator();
		while (it.hasNext()) {
			toReturn.add(toObjParuse((SbiObjParuse) it.next()));
		}
		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();
		}
	}
	return toReturn;
}
 
Example #24
Source File: RememberMeDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public void delete(Integer rememberMeId) throws EMFInternalError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		//String hql = "from SbiRememberMe srm where srm.id=" + rememberMeId;
		String hql = "from SbiRememberMe srm where srm.id=?" ;
		Query query = aSession.createQuery(hql);
		query.setInteger(0, rememberMeId.intValue());
		SbiRememberMe hibObj = (SbiRememberMe) query.uniqueResult();
		if (hibObj == null) {
			logger.warn("SbiRememberMe with id = " + rememberMeId + " not found!");
			return;
		}
		aSession.delete(hibObj);
		tx.commit();
	} catch (HibernateException he) {
		logException(he);
		if (tx != null) tx.rollback();	
		throw new EMFInternalError(EMFErrorSeverity.ERROR, "100");  
	} finally {
		if (aSession != null) {
			if (aSession.isOpen()) aSession.close();
		}
		logger.debug("OUT");
	}
}
 
Example #25
Source File: SubObjectDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void deleteSubObjectSameConnection(Integer idSub, Session aSession) throws EMFUserError {
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		SbiSubObjects hibSubobject = (SbiSubObjects) aSession.load(SbiSubObjects.class, idSub);
		SbiBinContents hibBinCont = hibSubobject.getSbiBinContents();

		// delete metadata eventually associated
		List metadata = DAOFactory.getObjMetadataDAO().loadAllObjMetadata();
		IObjMetacontentDAO objMetaContentDAO = DAOFactory.getObjMetacontentDAO();
		if (metadata != null && !metadata.isEmpty()) {
			Iterator it = metadata.iterator();
			while (it.hasNext()) {
				ObjMetadata objMetadata = (ObjMetadata) it.next();
				ObjMetacontent objMetacontent = DAOFactory.getObjMetacontentDAO().loadObjMetacontent(objMetadata.getObjMetaId(),
						hibSubobject.getSbiObject().getBiobjId(), hibSubobject.getSubObjId());
				if (objMetacontent != null) {
					objMetaContentDAO.eraseObjMetadata(objMetacontent);
				}
			}
		}

		aSession.delete(hibSubobject);
		aSession.delete(hibBinCont);
		tx.commit();
	} catch (HibernateException he) {
		logger.error(he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	}
	// finally {
	// if (aSession!=null){
	// if (aSession.isOpen()) aSession.close();
	// }
	// }
}
 
Example #26
Source File: SbiAccessibilityPreferencesDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public SbiAccessibilityPreferences readUserAccessibilityPreferences(String userId) throws EMFUserError {
	logger.debug("IN");
	SbiAccessibilityPreferences toReturn = null;
	Session aSession = null;
	Transaction tx = null;

	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		Criteria criteria = aSession.createCriteria(SbiAccessibilityPreferences.class);

		criteria.createAlias("user", "u").add(Restrictions.eq("u.userId", userId));
		// String q = "from SbiAccessibilityPreferences ";
		// Query query = aSession.createQuery(q);
		// query.setString("userId", userId);
		if (!criteria.list().isEmpty()) {
			toReturn = (SbiAccessibilityPreferences) criteria.list().get(0);
		}
		tx.commit();
	} catch (HibernateException he) {
		logger.error(he.getMessage(), he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
	logger.debug("OUT");

	return toReturn;
}
 
Example #27
Source File: SQLFunctionsInterSystemsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testSetProperties() throws Exception {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Simple simple = new Simple();
	simple.setName("Simple 1");
	s.save(simple, new Long(10) );
	Query q = s.createQuery("from Simple s where s.name=:name and s.count=:count");
	q.setProperties(simple);
	assertTrue( q.list().get(0)==simple );
	//misuse of "Single" as a propertyobject, but it was the first testclass i found with a collection ;)
	Single single = new Single() { // trivial hack to test properties with arrays.
		String[] getStuff() { return (String[]) getSeveral().toArray(new String[getSeveral().size()]); }
	};

	List l = new ArrayList();
	l.add("Simple 1");
	l.add("Slimeball");
	single.setSeveral(l);
	q = s.createQuery("from Simple s where s.name in (:several)");
	q.setProperties(single);
	assertTrue( q.list().get(0)==simple );


	q = s.createQuery("from Simple s where s.name in (:stuff)");
	q.setProperties(single);
	assertTrue( q.list().get(0)==simple );
	s.delete(simple);
	t.commit();
	s.close();
}
 
Example #28
Source File: _BaseRootDAO.java    From unitime with Apache License 2.0 5 votes vote down vote up
/**
 * Persist the given transient instance, first assigning a generated identifier. 
 * (Or using the current value of the identifier property if the assigned generator is used.) 
 */
public K save(T obj) {
	Transaction t = null;
	Session s = null;
	try {
		s = getSession();
		t = beginTransaction(s);
		K rtn = save(obj, s);
		commitTransaction(t);
		return rtn;
	} catch (HibernateException e) {
		if (null != t) t.rollback();
           throw e;
	}
}
 
Example #29
Source File: HibernateDao.java    From elepy with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteById(Serializable id) {
    try (Session session = sessionFactory.openSession()) {
        final Transaction transaction = session.beginTransaction();
        final T item = session.get(getType(), id);
        if (item != null) {
            session.delete(item);
        }

        transaction.commit();
    }
}
 
Example #30
Source File: SbiDsBcDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void deleteDsBc(SbiMetaDsBc aMeta) throws EMFUserError {
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		SbiMetaDsBcId hibId = new SbiMetaDsBcId();
		hibId.setBcId(aMeta.getId().getBcId());
		hibId.setDsId(aMeta.getId().getDsId());
		hibId.setOrganization(aMeta.getId().getOrganization());
		hibId.setVersionNum(aMeta.getId().getVersionNum());

		SbiMetaDsBc hib = (SbiMetaDsBc) aSession.load(SbiMetaDsBc.class, hibId);

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

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

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

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

}