Java Code Examples for org.hibernate.Transaction#commit()

The following examples show how to use org.hibernate.Transaction#commit() . 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: MasterDetailTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testSelfManyToOne() throws Exception {

		//if (dialect instanceof HSQLDialect) return;

		Session s = openSession();
		Transaction t = s.beginTransaction();
		Master m = new Master();
		m.setOtherMaster(m);
		s.save(m);
		t.commit();
		s.close();
		s = openSession();
		t = s.beginTransaction();
		Iterator i = s.iterate("from Master");
		m = (Master) i.next();
		assertTrue( m.getOtherMaster()==m );
		if (getDialect() instanceof HSQLDialect) { m.setOtherMaster(null); s.flush(); }
		s.delete(m);
		t.commit();
		s.close();
	}
 
Example 2
Source File: CRUDTest.java    From Project with Apache License 2.0 6 votes vote down vote up
@Test
public void addTest(){
    Configuration configuration = new Configuration();
    configuration.configure();

    SessionFactory sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    User user = new User();
    user.setUsername("GJXAIOU");
    user.setPassword("GJXAIOU");
    user.setAddress("江苏");
    session.save(user);

    transaction.commit();

    session.close();
    sessionFactory.close();
}
 
Example 3
Source File: DBQueryUtil.java    From kardio with Apache License 2.0 6 votes vote down vote up
/**
 * get CurrentHealth Check Details from DB.
 * 
 * @param componentId
 * @param environmentId
 * @param regionID
 * @param healthCheckType
 * @return
 * @
 */
private static HealthCheckVO getCurrentHealthCheckDetails(final int componentId, final int environmentId,
		final long regionID,final HealthCheckType healthCheckType) {
	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	Criteria hcCrit = session.createCriteria(HealthCheckEntity.class,"hc");
	hcCrit.add(Restrictions.eq("hc.component.componentId", componentId));
	hcCrit.add(Restrictions.eq("hc.environment.environmentId", environmentId));
	hcCrit.add(Restrictions.eq("hc.region.regionId", regionID));
	if(healthCheckType != null) {
		hcCrit.add(Restrictions.eq("hc.healthCheckType.healthCheckTypeId", healthCheckType.getHealthCheckTypeId()));
	}
	hcCrit.setMaxResults(1);
	HealthCheckEntity hcEnt = (HealthCheckEntity) hcCrit.uniqueResult();
	txn.commit();
	if(hcEnt == null){
		return null;
	}
	HealthCheckVO hcVO = new HealthCheckVO();
	hcVO.setHealthCheckId(hcEnt.getHealthCheckId());
	if(hcEnt.getCurrentStatus() != null){
		hcVO.setCurrentStatus(hcEnt.getCurrentStatus().getStatusId());
	}
	return hcVO;
}
 
Example 4
Source File: ASTParserLoadingTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testAggregation() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Human h = new Human();
	h.setBodyWeight( (float) 74.0 );
	h.setHeight(120.5);
	h.setDescription("Me");
	h.setName( new Name("Gavin", 'A', "King") );
	h.setNickName("Oney");
	s.persist(h);
	Double sum = (Double) s.createQuery("select sum(h.bodyWeight) from Human h").uniqueResult();
	Double avg = (Double) s.createQuery("select avg(h.height) from Human h").uniqueResult();
	assertEquals(sum.floatValue(), 74.0, 0.01);
	assertEquals(avg.doubleValue(), 120.5, 0.01);
	Long id = (Long) s.createQuery("select max(a.id) from Animal a").uniqueResult();
	s.delete(h);
	t.commit();
	s.close();
}
 
Example 5
Source File: DataDbLogger.java    From core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Store just a single object into data. This is slower than batching a few
 * at a time. Should be used when the batching encounters an exception. This
 * way can still store all of the good data from a batch.
 * 
 * @param o
 */
private void processSingleObject(Object objectToBeStored) {
	Session session = null;
	Transaction tx = null;
	try {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		logger.debug("Individually saving object {}", objectToBeStored);
		session.save(objectToBeStored);
		tx.commit();
	} catch (HibernateException e) {
		if (tx != null) {
			try {
				tx.rollback();
			} catch (HibernateException e2) {
				logger.error("Error rolling back transaction in "
						+ "processSingleObject(). ", e2);
			}
		}
	} finally {			
		if (session != null)
			session.close();
	}
}
 
Example 6
Source File: ObjTemplateDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ObjTemplate getBIObjectActiveTemplate(Integer biobjId) throws EMFInternalError {
	ObjTemplate objTemp = new ObjTemplate();
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		// String hql = "from SbiObjTemplates sot where sot.active=true and sot.sbiObject.biobjId="+biobjId;
		String hql = "from SbiObjTemplates sot where sot.active=? and sot.sbiObject.biobjId=? and sot.commonInfo.organization = ?";

		Query query = aSession.createQuery(hql);
		query.setBoolean(0, true);
		query.setInteger(1, biobjId.intValue());
		query.setString(2, getTenant());
		SbiObjTemplates hibObjTemp = (SbiObjTemplates) query.uniqueResult();
		if (hibObjTemp == null) {
			objTemp = null;
		} else {
			objTemp = toObjTemplate(hibObjTemp);
		}
		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();
		}
	}
	return objTemp;
}
 
Example 7
Source File: SbiUserDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Get value of failed login attemtpts counter from DB.
 *
 * @author Marco Libanori
 */
@Override
public int getFailedLoginAttempts(String userId) {
	logger.debug("IN");

	Session aSession = null;
	Transaction tx = null;
	try {

		Integer result = 0;

		if (isUserIdAlreadyInUse(userId) != null) {

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

			ProjectionList projList = Projections.projectionList().add(Projections.property("failedLoginAttempts"), "failedLoginAttempts");

			SimpleExpression eq = Restrictions.eq("userId", userId);

			result = (Integer) aSession.createCriteria(SbiUser.class).add(eq).setProjection(projList).uniqueResult();

			tx.commit();
		}

		return result;
	} catch (HibernateException he) {
		if (tx != null)
			tx.rollback();
		throw new SpagoBIDAOException("Error while reading failed login attempts counter for user " + userId, he);
	} finally {
		logger.debug("OUT");
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
}
 
Example 8
Source File: SbiGeoMapFeaturesDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Insert map features.
 * 
 * @param aMapFeature the a map feature
 * 
 * @throws EMFUserError the EMF user error
 * 
 * @see it.eng.spagobi.mapcatalogue.dao.geo.bo.dao.ISbiGeoMapFeaturesDAO#insertMapFeatures(it.eng.spagobi.geo.bo.SbiGeoMapFeatures)
 */
public void insertMapFeatures(GeoMapFeature aMapFeature) throws EMFUserError {
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		SbiGeoMapFeatures hibMapFeature = new SbiGeoMapFeatures();	
		
		SbiGeoMapFeaturesId hibMapFeatureId = new SbiGeoMapFeaturesId();			
		hibMapFeatureId.setMapId(aMapFeature.getMapId());
		hibMapFeatureId.setFeatureId(aMapFeature.getFeatureId());
		hibMapFeature.setId(hibMapFeatureId);
		
		hibMapFeature.setSvgGroup(aMapFeature.getSvgGroup());
		hibMapFeature.setVisibleFlag(aMapFeature.getVisibleFlag());
		updateSbiCommonInfo4Insert(hibMapFeature);
		aSession.save(hibMapFeature);
		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();
		}			
	}
}
 
Example 9
Source File: DBQueryUtil.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * Function to execute a delete statement..
 * 
 * @param query
 */
public static void executeDelete(String query) {
	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	session.createSQLQuery(query).executeUpdate();
	txn.commit();
}
 
Example 10
Source File: MetaModelParviewDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List loadMetaModelParviewsFather(Integer metaModelParId) {
	List<MetaModelParview> toReturn = new ArrayList();
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		String hql = "from SbiMetaModelParview s where s.sbiMetaModelFather.metaModelParId = ? order by s.prog";
		Query hqlQuery = aSession.createQuery(hql);
		hqlQuery.setInteger(0, metaModelParId.intValue());
		List sbiMetaModelParviews = hqlQuery.list();
		Iterator it = sbiMetaModelParviews.iterator();
		while (it.hasNext()) {
			toReturn.add(toMetaModelParview((SbiMetaModelParview) 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 11
Source File: UnionSubclassTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testUnionSubclassFetchMode() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Location mel = new Location("Earth");
	s.save(mel);
	
	Human gavin = new Human();
	gavin.setIdentity("gavin");
	gavin.setSex('M');
	gavin.setLocation(mel);
	mel.addBeing(gavin);
	Human max = new Human();
	max.setIdentity("max");
	max.setSex('M');
	max.setLocation(mel);
	mel.addBeing(gavin);
	
	s.flush();
	s.clear();
	
	List list = s.createCriteria(Human.class)
		.setFetchMode("location", FetchMode.JOIN)
		.setFetchMode("location.beings", FetchMode.JOIN)
		.list();
	
	for (int i=0; i<list.size(); i++ ) {
		Human h = (Human) list.get(i);
		assertTrue( Hibernate.isInitialized( h.getLocation() ) );
		assertTrue( Hibernate.isInitialized( h.getLocation().getBeings() ) );
		s.delete(h);
	}
	s.delete( s.get( Location.class, new Long(mel.getId()) ) );
	t.commit();
	s.close();
	
	
}
 
Example 12
Source File: I18NMessagesDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void updateNonDefaultI18NMessagesLabel(SbiI18NMessages oldMessage, SbiI18NMessages newMessage) {
	logger.debug("IN");
	Session session = null;
	Transaction tx = null;
	try {
		session = getSession();
		tx = session.beginTransaction();
		String tenant = getTenant();
		List<SbiI18NMessages> messages = getSbiI18NMessagesByLabel(oldMessage, tenant, session);
		Iterator<SbiI18NMessages> it = messages.iterator();
		while (it.hasNext()) {
			SbiI18NMessages toModify = it.next();
			toModify.setLabel(newMessage.getLabel());
			updateSbiCommonInfo4Update(toModify);
			session.update(toModify);
			session.flush();
		}
		tx.commit();
	} catch (HibernateException e) {
		logException(e);
		if (tx != null)
			tx.rollback();
		throw new RuntimeException();
	} finally {
		if (session != null) {
			if (session.isOpen())
				session.close();
		}
	}
	logger.debug("OUT");
}
 
Example 13
Source File: CustomerAccountDaoImpl.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
@Transactional
@Override
public void setCustomerProfile(CustomerAccount account) {
	Session session = this.sessionFactory.openSession();
	Transaction transaction = session.beginTransaction();

	session.persist(account);
	transaction.commit();
	session.close();


}
 
Example 14
Source File: UserDAOImpl.java    From journaldev with MIT License 5 votes vote down vote up
@Override
public User getUserByCredentials(String userId, String password) {
	Session session = sf.openSession();
	Transaction tx = session.beginTransaction();
	Query query = session.createQuery("from User where id=:id and pwd=:pwd");
	query.setString("id", userId); query.setString("pwd", password);
	User user = (User) query.uniqueResult();
	if(user != null){
		System.out.println("User Retrieved from DB::"+user);
	}
	tx.commit();session.close();
	return user;
}
 
Example 15
Source File: DBService.java    From stepic_java_webserver with MIT License 5 votes vote down vote up
public long addUser(String name) throws DBException {
    try {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        UsersDAO dao = new UsersDAO(session);
        long id = dao.insertUser(name);
        transaction.commit();
        session.close();
        return id;
    } catch (HibernateException e) {
        throw new DBException(e);
    }
}
 
Example 16
Source File: ProgressThreadDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<ProgressThread> loadNotClosedProgressThreadsByUserId(String userId) throws EMFUserError {
	// logger.debug("IN");
	List<ProgressThread> toReturn = null;

	Session aSession = null;
	Transaction tx = null;

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

		Query hibPT = aSession.createQuery("from SbiProgressThread h where h.userId = ? AND h.status != 'CLOSED'");
		hibPT.setString(0, userId);

		List sbiProgressThreadList = hibPT.list();
		if (sbiProgressThreadList != null) {
			toReturn = new ArrayList<ProgressThread>();
			for (Iterator iterator = sbiProgressThreadList.iterator(); iterator.hasNext();) {
				SbiProgressThread sbiPT = (SbiProgressThread) iterator.next();
				ProgressThread pT = toProgressThread(sbiPT);
				toReturn.add(pT);
			}
		}

		tx.commit();

	} catch (HibernateException he) {
		logger.error("Error while loading Progress Threads with userId" + userId + " and status NOT CLOSED", he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
			// logger.debug("OUT");
		}
	}
	// logger.debug("OUT");
	return toReturn;
}
 
Example 17
Source File: ExamDistributionPrefsAction.java    From unitime with Apache License 2.0 4 votes vote down vote up
/**
  * Delete distribution pref
  * @param distPrefId
  */
 private void doDelete(HttpServletRequest request, String distPrefId) {
     Transaction tx = null;
     
     sessionContext.checkPermission(distPrefId, "DistributionPref", Right.ExaminationDistributionPreferenceDelete);

     try {
         
      DistributionPrefDAO dpDao = new DistributionPrefDAO();
      org.hibernate.Session hibSession = dpDao.getSession();
      tx = hibSession.getTransaction();
      if (tx==null || !tx.isActive())
          tx = hibSession.beginTransaction();
      
         HashSet relatedExams = new HashSet();
      DistributionPref dp = dpDao.get(new Long(distPrefId));
      PreferenceGroup owner = (PreferenceGroup) dp.getOwner();
      owner.getPreferences().remove(dp);
for (Iterator i=dp.getDistributionObjects().iterator();i.hasNext();) {
	DistributionObject dObj = (DistributionObject)i.next();
	PreferenceGroup pg = dObj.getPrefGroup();
	relatedExams.add(pg);
	pg.getDistributionObjects().remove(dObj);
	hibSession.saveOrUpdate(pg);
}
      
      hibSession.delete(dp);
      hibSession.saveOrUpdate(owner);
      
         for (Iterator i=relatedExams.iterator();i.hasNext();) {
             Exam exam = (Exam)i.next();
             ChangeLog.addChange(
                     hibSession, 
                     sessionContext, 
                     exam, 
                     ChangeLog.Source.DIST_PREF_EDIT,
                     ChangeLog.Operation.DELETE,
                     exam.firstSubjectArea(), 
                     exam.firstDepartment());
         }

         if (tx!=null && tx.isActive()) 
          tx.commit();
      
      hibSession.flush();
      hibSession.refresh(owner);
     }
     catch (Exception e) {
         Debug.error(e);
         if (tx!=null && tx.isActive()) 
             tx.rollback();
     }
 }
 
Example 18
Source File: EngineDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<Engine> loadAllEnginesForBIObjectTypeAndTenant(String biobjectType) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;

	logger.debug("BiObject Type is " + biobjectType);
	Set<String> addedEngines = new HashSet<String>();
	List<Engine> realResult = new ArrayList<Engine>();
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		Query hibQueryProd = aSession.createQuery("select opt.sbiProductType from SbiOrganizationProductType opt "
				+ "where opt.sbiOrganizations.name = :tenant ");
		hibQueryProd.setString("tenant", getTenant());

		List hibListProd = hibQueryProd.list();
		Iterator productIt = hibListProd.iterator();

		while (productIt.hasNext()) {
			SbiProductType productType = (SbiProductType) productIt.next();

			Query hibQueryEng = aSession.createQuery("select pte.sbiEngines from SbiProductTypeEngine pte "
					+ "where pte.sbiProductType.label = :productType " + "and pte.sbiEngines.biobjType.valueCd = :biobjectType");

			hibQueryEng.setString("productType", productType.getLabel());
			hibQueryEng.setString("biobjectType", biobjectType);

			List hibListEngine = hibQueryEng.list();
			Iterator engineIt = hibListEngine.iterator();
			while (engineIt.hasNext()) {
				SbiEngines sbiEngine = (SbiEngines) engineIt.next();
				if (addedEngines.add(sbiEngine.getLabel())) {
					realResult.add(toEngine(sbiEngine));
				}
			}
		}
		tx.commit();
	} catch (HibernateException he) {
		logger.debug("Error in loading ecgines for biObject Type " + biobjectType, he);
		logException(he);

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

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
	if (realResult.isEmpty()) {
		logger.debug("No engines was found.");
	}
	logger.debug("OUT");
	return realResult;
}
 
Example 19
Source File: ParentChildTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testManyToMany() throws Exception {

		Session s = openSession();
		Transaction t = s.beginTransaction();
		Container c = new Container();
		c.setManyToMany( new ArrayList() );
		c.setBag( new ArrayList() );
		Simple s1 = new Simple();
		Simple s2 = new Simple();
		s1.setCount(123); s2.setCount(654);
		Contained c1 = new Contained();
		c1.setBag( new ArrayList() );
		c1.getBag().add(c);
		c.getBag().add(c1);
		c.getManyToMany().add(s1);
		c.getManyToMany().add(s2);
		Serializable cid = s.save(c); //s.save(c1);
		s.save(s1, new Long(12) ); s.save(s2, new Long(-1) );
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		c = (Container) s.load(Container.class, cid);
		assertTrue( c.getBag().size()==1 );
		assertTrue( c.getManyToMany().size()==2 );
		c1 = (Contained) c.getBag().iterator().next();
		assertTrue( c.getBag().size()==1 );
		c.getBag().remove(c1);
		c1.getBag().remove(c);
		assertTrue( c.getManyToMany().remove(0)!=null );
		t.commit();
		s.close();

		s = openSession();
		t = s.beginTransaction();
		c = (Container) s.load(Container.class, cid);
		assertTrue( c.getBag().size()==0 );
		assertTrue( c.getManyToMany().size()==1 );
		c1 = (Contained) s.load( Contained.class, new Long(c1.getId()) );
		assertTrue( c1.getBag().size()==0 );
		assertTrue( s.delete("from ContainerX c")==1 );
		assertTrue( s.delete("from Contained")==1 );
		assertTrue( s.delete("from Simple")==2 );
		t.commit();
		s.close();
	}
 
Example 20
Source File: SbiNewsReadDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Integer insertNewsRead(Integer id, UserProfile profile) {

	Session session = null;
	Transaction transaction = null;
	SbiNews sbiNews;

	try {

		if (getNewsReadByIdAndUser(id, String.valueOf(profile.getUserId())) != null) {
			throw new SpagoBIRuntimeException("The message is alredy read");
		}

		SbiNewsDAOImpl newsDAO = new SbiNewsDAOImpl();
		sbiNews = newsDAO.getSbiNewsById(id, profile);

		if (sbiNews.getId() != null) {

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

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

				SbiNewsRead newsRead = new SbiNewsRead();
				newsRead.setUser(String.valueOf(profile.getUserId()));
				newsRead.setNewsId(id);

				updateSbiCommonInfo4Insert(newsRead);
				session.save(newsRead);
				transaction.commit();

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

		} else {

			throw new SpagoBIRuntimeException("An error has occured while getting news by id!");
		}

	} catch (HibernateException e) {
		if (transaction != null)
			transaction.rollback();
		throw new SpagoBIRuntimeException("Cannot insert", e);

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

	logger.debug("OUT");
	return id;
}