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

The following examples show how to use org.hibernate.Session#close() . 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: Main.java    From maven-framework-project with MIT License 6 votes vote down vote up
public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();
		
		Department department = new Department();
		department.setDepartmentName("Sales");
		session.save(department);

		Employee emp1 = new Employee("Nina", "Mayers", "111");
		Employee emp2 = new Employee("Tony", "Almeida", "222");
		
		department.setEmployees(new Employee[] {emp1, emp2});
		
		session.save(department);

		session.getTransaction().commit();
		session.close();
	}
 
Example 2
Source File: TransactionIsolationExternalDataSourceConnectionProviderTest.java    From hibernate-master-class with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    Session session = null;
    Transaction txn = null;
    try {
        session = getSessionFactory().openSession();
        txn = session.beginTransaction();
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation()));
            }
        });
        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive() ) txn.rollback();
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
 
Example 3
Source File: ResultCheckStyleTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testDeleteWithExceptionChecking() {
	Session s = openSession();
	s.beginTransaction();
	ExceptionCheckingEntity e = new ExceptionCheckingEntity();
	e.setId( new Long( 1 ) );
	e.setName( "dummy" );
	s.delete( e );
	try {
		s.flush();
		fail( "expection flush failure!" );
	}
	catch( JDBCException ex ) {
		// these should specifically be JDBCExceptions...
	}
	s.clear();
	s.getTransaction().commit();
	s.close();
}
 
Example 4
Source File: UdpDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public void delete(SbiUdp prop) {
	logger.debug("IN");
	Session session = getSession();
	Transaction tx = null;
	try {
		tx = session.beginTransaction();
		session.delete(prop);
		tx.commit();

	} catch (HibernateException e) {
		if( tx != null && tx.isActive() ){
			tx.rollback();
		}
		throw e;

	}finally{
		session.close();
	}
	logger.debug("OUT");
}
 
Example 5
Source File: ParameterDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load all parameters.
 *
 * @return the list
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IParameterDAO#loadAllParameters()
 */
@Override
public List loadAllParameters() throws EMFUserError {
	Session aSession = null;
	Transaction tx = null;
	List realResult = new ArrayList();
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		Query hibQuery = aSession.createQuery(" from SbiParameters");
		List hibList = hibQuery.list();

		Iterator it = hibList.iterator();

		while (it.hasNext()) {
			realResult.add(toParameter((SbiParameters) it.next()));
		}
		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();
		}
	}
	return realResult;
}
 
Example 6
Source File: CatalogFunctionDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public SbiCatalogFunction getCatalogFunctionById(int id) {

    Session session;
    Transaction transaction = null;
    SbiCatalogFunction sbiCatalogFunction = null;

    logger.debug("IN");

    session = null;
    try {

        session = getSession();
        Assert.assertNotNull(session, "session cannot be null");
        transaction = session.beginTransaction();
        sbiCatalogFunction = (SbiCatalogFunction) session.get(SbiCatalogFunction.class, id);
        transaction.commit();

    } catch (Throwable t) {
        if (transaction != null && transaction.isActive()) {
            transaction.rollback();
        }
        throw new SpagoBIDAOException("An error occured while reading Catalog Functions from DB", t);

    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
        logger.debug("OUT");
    }
    return sbiCatalogFunction;

}
 
Example 7
Source File: OrphanTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testOrphanDeleteOnDelete() {
	Session session = openSession();
	Transaction t = session.beginTransaction();
	Product prod = new Product();
	prod.setName("Widget");
	Part part = new Part();
	part.setName("Widge");
	part.setDescription("part if a Widget");
	prod.getParts().add(part);
	Part part2 = new Part();
	part2.setName("Get");
	part2.setDescription("another part if a Widget");
	prod.getParts().add(part2);
	session.persist(prod);
	session.flush();
	
	prod.getParts().remove(part);
	
	session.delete(prod);
	
	t.commit();
	session.close();
	
	session = openSession();
	t = session.beginTransaction();
	assertNull( session.get(Part.class, "Widge") );
	assertNull( session.get(Part.class, "Get") );
	assertNull( session.get(Product.class, "Widget") );
	t.commit();
	session.close();
}
 
Example 8
Source File: LovDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Modify modalities value.
 *
 * @param aModalitiesValue
 *            the a modalities value
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.behaviouralmodel.lov.dao.IModalitiesValueDAO#modifyModalitiesValue(it.eng.spagobi.behaviouralmodel.lov.bo.ModalitiesValue)
 */
@Override
public void modifyModalitiesValue(ModalitiesValue aModalitiesValue) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		SbiLov hibLov = (SbiLov) aSession.load(SbiLov.class, aModalitiesValue.getId());
		hibLov.setName(aModalitiesValue.getName());
		hibLov.setLabel(aModalitiesValue.getLabel());
		hibLov.setDescr(aModalitiesValue.getDescription());
		SbiDomains inpType = (SbiDomains) aSession.load(SbiDomains.class, new Integer(aModalitiesValue.getITypeId()));
		hibLov.setInputType(inpType);
		hibLov.setInputTypeCd(aModalitiesValue.getITypeCd());
		hibLov.setLovProvider(aModalitiesValue.getLovProvider());
		updateSbiCommonInfo4Update(hibLov);
		tx.commit();
	} catch (HibernateException he) {
		logger.error("HibernateException", 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 9
Source File: SbiDataSetDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Integer countSbiDataSet(String search, Integer[] ids) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	Integer resultNumber;

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

		String hql = "select count(*) from SbiDataSet where active=true and label like '%" + search + "%'" + getIdsWhereClause(ids);
		Query hqlQuery = aSession.createQuery(hql);
		Long temp = (Long) hqlQuery.uniqueResult();
		resultNumber = new Integer(temp.intValue());

	} catch (HibernateException he) {
		logger.error("Error while loading the list of SbiDataSet", he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 9104);

	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
			logger.debug("OUT");
		}
	}
	return resultNumber;
}
 
Example 10
Source File: OrphanTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testOrphanDeleteAfterPersist() {
	Session session = openSession();
	Transaction t = session.beginTransaction();
	Product prod = new Product();
	prod.setName("Widget");
	Part part = new Part();
	part.setName("Widge");
	part.setDescription("part if a Widget");
	prod.getParts().add(part);
	Part part2 = new Part();
	part2.setName("Get");
	part2.setDescription("another part if a Widget");
	prod.getParts().add(part2);
	session.persist(prod);
	
	prod.getParts().remove(part);
	
	t.commit();
	session.close();
	
	session = openSession();
	t = session.beginTransaction();
	assertNull( session.get(Part.class, "Widge") );
	assertNotNull( session.get(Part.class, "Get") );
	session.delete( session.get(Product.class, "Widget") );
	t.commit();
	session.close();
}
 
Example 11
Source File: BackrefCompositeMapKeyTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testOrphanDeleteOnMerge() {
	Session session = openSession();
	Transaction t = session.beginTransaction();
	Product prod = new Product( "Widget" );
	Part part = new Part( "Widge", "part if a Widget" );
	MapKey mapKey = new MapKey( "Top" );
	prod.getParts().put( mapKey, part );
	Part part2 = new Part( "Get", "another part if a Widget" );
	prod.getParts().put( new MapKey("Bottom"), part2 );
	session.persist( prod );
	t.commit();
	session.close();

	prod.getParts().remove( mapKey );

	session = openSession();
	t = session.beginTransaction();
	session.merge(prod);
	t.commit();
	session.close();

	session = openSession();
	t = session.beginTransaction();
	assertNull( session.get(Part.class, "Widge") );
	assertNotNull( session.get(Part.class, "Get") );
	session.delete( session.get(Product.class, "Widget") );
	t.commit();
	session.close();
}
 
Example 12
Source File: AbstractHibernateConnectionCheckListModule.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
public void createCheckedObjectMap(SourceBean request) throws Exception {
		checkedObjectsMap = new HashMap();

		// get CHECKED_QUERY query parameters

		String[] parameters = getQueryParameters("CHECKED_QUERY", request);

		// get CHECKED_QUERY statment
		String statement = getQueryStatement("CHECKED_QUERY", parameters);

		Session aSession = null;
		Transaction tx = null;
		
		// exec CHECKED_QUERY
		ScrollableDataResult scrollableDataResult = null;
		SQLCommand sqlCommand = null;
		DataConnection dataConnection = null;
		DataResult dataResult = null;
		try {
			aSession = HibernateSessionManager.getCurrentSession();
			tx = aSession.beginTransaction();
			//Connection jdbcConnection = aSession.connection();
			Connection jdbcConnection = HibernateSessionManager.getConnection(aSession);
			dataConnection = DelegatedHibernateConnectionListService.getDataConnection(jdbcConnection);
        	sqlCommand = dataConnection.createSelectCommand(statement);
        	dataResult = sqlCommand.execute();
        	scrollableDataResult = (ScrollableDataResult) dataResult.getDataObject();
			SourceBean chekedObjectsBean = scrollableDataResult.getSourceBean();
			List checkedObjectsList = chekedObjectsBean
					.getAttributeAsList("ROW");
			for (int i = 0; i < checkedObjectsList.size(); i++) {
				SourceBean objects = (SourceBean) checkedObjectsList.get(i);
				String key = getObjectKey(objects);
				checkedObjectsMap.put(key, key);
			}
			
//			aSession.doWork(new MyWork(statement));
			
//			tx.commit();
		} catch (HibernateException he) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, 
		            this.getClass().getName(), 
		            "execCheckedQuery", 
		            he.getMessage());
			if (tx != null)
				tx.rollback();
			throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
		} catch (Exception e) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, this.getClass()
					.getName(), "createCheckedObjectMap", e.getMessage(), e);
		} finally {
			if (aSession != null) {
				if (aSession.isOpen()) aSession.close();
			}
		}
	}
 
Example 13
Source File: LowFunctionalityDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<LowFunctionality> loadFunctionalitiesForSharing(Integer docId) {
	logger.debug("IN");
	Session session = null;
	List<LowFunctionality> toReturn = new ArrayList<>();
	List<SbiFunctions> hibList = new ArrayList<>();
	IEngUserProfile profile;

	try {
		StringBuffer statement = new StringBuffer("from SbiFunctions f ");
		profile = getUserProfile();
		String username = (String) ((UserProfile) profile).getUserId();
		boolean isFinalUser = false;

		if (profile != null && profile.isAbleToExecuteAction("ViewMyFolderAdmin")) {
			statement.append("where (f.functTypeCd = 'LOW_FUNCT' or f.functTypeCd = 'USER_FUNCT')");
		} else if (username == null) {
			statement.append("where f.functTypeCd = 'LOW_FUNCT'");
		} else {
			isFinalUser = true;
			statement.append("where (f.functTypeCd = 'LOW_FUNCT' or f.path = :path)");
		}

		statement.append(" and f.functId not in (select distinct obf.id.sbiFunctions.functId from SbiObjFunc obf where obf.id.sbiObjects.biobjId = :docId)")
				.append(" order by f.parentFunct.functId, f.prog");
		session = getSession();
		Query query = session.createQuery(statement.toString());

		if (username != null && isFinalUser) {
			query.setString("path", "/" + username);
		}
		query.setInteger("docId", docId);
		hibList = query.list();
		Iterator<SbiFunctions> it = hibList.iterator();
		while (it.hasNext()) {
			LowFunctionality funct = toLowFunctionality(it.next(), false, null, null);
			toReturn.add(funct);
		}
	} catch (Exception e) {
		logger.error("Cannot load functionalities for sharing", e);
		throw new SpagoBIDAOException("Cannot load functionalities for sharing", e);
	} finally {
		if (session != null && session.isOpen())
			session.close();
	}

	logger.debug("OUT");
	return toReturn;
}
 
Example 14
Source File: SubreportDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List loadSubreportsBySubRptId(Integer sub_rpt_id) throws EMFUserError {
	Session aSession = null;
	Transaction tx = null;
	List realResult = new ArrayList();
	String hql = null;
	Query hqlQuery = null;

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

		// hql = " from SbiSubreports as subreport " +
		// "where subreport.id.subReport.biobjId = " + sub_rpt_id.toString();

		hql = " from SbiSubreports as subreport " + "where subreport.id.subReport.biobjId = ?";

		hqlQuery = aSession.createQuery(hql);
		hqlQuery.setInteger(0, sub_rpt_id.intValue());
		List hibList = hqlQuery.list();

		Iterator it = hibList.iterator();

		while (it.hasNext()) {
			realResult.add(toSubreport((SbiSubreports) it.next()));
		}
		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();
		}
	}
	return realResult;
}
 
Example 15
Source File: RoleDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Associate a Meta Model Category to the role
 *
 * @see it.eng.spagobi.commons.dao.IRoleDAO#insertRoleMetaModelCategory(java.lang.Integer, java.lang.Integer)
 */
@Override
public void insertRoleMetaModelCategory(Integer roleId, Integer categoryId) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		SbiExtRoles hibRole = (SbiExtRoles) aSession.load(SbiExtRoles.class, roleId);

		SbiDomains category = (SbiDomains) aSession.load(SbiDomains.class, categoryId);

		Set<SbiDomains> metaModelCategories = hibRole.getSbiMetaModelCategories();
		if (metaModelCategories == null) {
			metaModelCategories = new HashSet<SbiDomains>();
		}
		metaModelCategories.add(category);
		hibRole.setSbiMetaModelCategories(metaModelCategories);

		aSession.saveOrUpdate(hibRole);
		aSession.flush();

		updateSbiCommonInfo4Update(hibRole);
		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();
				logger.debug("The [insertRoleMetaModelCategory] occurs. Role cache will be cleaned.");
				this.clearCache();
			}
			logger.debug("OUT");

		}
	}

}
 
Example 16
Source File: EventLogDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Insert event log.
 *
 * @param eventLog
 *            the event log
 *
 * @return the integer
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.events.dao.IEventLogDAO#insertEventLog(it.eng.spagobi.events.bo.EventLog)
 */
@Override
public Integer insertEventLog(EventLog eventLog) throws EMFUserError {
	logger.debug("IN");
	Session session = null;
	Transaction tx = null;
	try {
		session = getSession();
		tx = session.beginTransaction();

		SbiEventsLog hibEventLog = new SbiEventsLog();
		hibEventLog.setUser(eventLog.getUser());
		hibEventLog.setDate(eventLog.getDate());
		hibEventLog.setDesc(eventLog.getDesc());
		hibEventLog.setParams(eventLog.getParams());
		hibEventLog.setEventType(eventLog.getType());
		this.updateSbiCommonInfo4Insert(hibEventLog);
		Set hibEventRoles = new HashSet();
		List roles = eventLog.getRoles();
		Iterator rolesIt = roles.iterator();
		while (rolesIt.hasNext()) {
			String roleName = (String) rolesIt.next();
			String hql = "from SbiExtRoles as roles where roles.name = ?";

			Query hqlQuery = session.createQuery(hql);
			hqlQuery.setString(0, roleName);
			SbiExtRoles aHibRole = (SbiExtRoles) hqlQuery.uniqueResult();
			if (aHibRole == null) {
				logger.error("Role with name = '" + roleName + "' does not exist!!");
				continue;
			}
			hibEventRoles.add(aHibRole);
		}
		hibEventLog.setRoles(hibEventRoles);
		session.save(hibEventLog);
		tx.commit();
		return hibEventLog.getId();
	} catch (HibernateException he) {
		logException(he);

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {
		if (session != null) {
			if (session.isOpen())
				session.close();
		}
		logger.debug("OUT");
	}
}
 
Example 17
Source File: SbiJobTableDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<SbiMetaJob> loadJobsByTableId(Integer tableId) throws EMFUserError {
	logger.debug("IN");

	Session aSession = null;
	Transaction tx = null;
	List<SbiMetaJob> toReturn = new ArrayList();
	Query hqlQuery = null;

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

		hqlQuery = aSession.createQuery(" from SbiMetaJobTable as db where db.id.tableId = ? ");
		hqlQuery.setInteger(0, tableId);
		List hibList = hqlQuery.list();

		Iterator it = hibList.iterator();
		while (it.hasNext()) {
			SbiMetaJobTable tmpRel = (SbiMetaJobTable) it.next();
			SbiMetaJob tmpJob = DAOFactory.getSbiMetaJobDAO().loadJobByID(new Integer(tmpRel.getId().getJobId()));

			if (tmpJob != null)
				toReturn.add(tmpJob);
		}
		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();
		}
	}
	logger.debug("OUT");
	return toReturn;
}
 
Example 18
Source File: SbiDsBcDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<SbiMetaBc> loadBcByDsId(Integer dsId) throws EMFUserError {
	logger.debug("IN");

	Session aSession = null;
	Transaction tx = null;
	List<SbiMetaBc> toReturn = new ArrayList();
	Query hqlQuery = null;

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

		hqlQuery = aSession.createQuery(" from SbiMetaDsBc as db where db.id.dsId = ? ");
		hqlQuery.setInteger(0, dsId);
		List hibList = hqlQuery.list();

		Iterator it = hibList.iterator();
		while (it.hasNext()) {
			SbiMetaDsBc tmpRel = (SbiMetaDsBc) it.next();
			SbiMetaBc tmpBC = DAOFactory.getSbiMetaBCDAO().loadBcByID(new Integer(tmpRel.getId().getBcId()));

			if (tmpBC != null)
				toReturn.add(tmpBC);
		}
		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();
		}
	}
	logger.debug("OUT");
	return toReturn;
}
 
Example 19
Source File: HibernateNoSessionUnitTest.java    From tutorials with MIT License 3 votes vote down vote up
@Test
public void whenAccessUserRolesInsideSession_thenSuccess() {

    User detachedUser = createUserWithRoles();

    Session session = sessionFactory.openSession();
    session.beginTransaction();

    User persistentUser = session.find(User.class, detachedUser.getId());

    Assert.assertEquals(2, persistentUser.getRoles().size());

    session.getTransaction().commit();
    session.close();
}
 
Example 20
Source File: HibernateTemplate.java    From MogwaiERDesignerNG with GNU General Public License v3.0 3 votes vote down vote up
public Object execute() throws Exception {
    ThreadbasedConnectionProvider.initializeForThread(connection);
    Session theSession = null;
    Transaction theTx = null;

    Thread theCurrentThread = Thread.currentThread();

    ClassLoader theLoader = HibernateTemplate.class.getClassLoader();
    theCurrentThread.setContextClassLoader(theLoader);

    try {

        theSession = createSession(connection, dialectClass);

        theTx = theSession.beginTransaction();

        Object theResult = doInSession(theSession);

        theTx.commit();

        return theResult;

    } catch (Exception e) {
        if (theTx != null) {
            theTx.rollback();
        }

        throw e;
    } finally {

        if (theSession != null) {
            theSession.close();
        }

        ThreadbasedConnectionProvider.cleanup();
    }
}