Java Code Examples for org.hibernate.Transaction

The following examples show how to use org.hibernate.Transaction. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: ALLGO   Source File: EventDAOimpl.java    License: 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 2
Source Project: hibernate-master-class   Source File: AbstractTest.java    License: 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 3
Source Project: unitime   Source File: LogCleaner.java    License: 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 4
Source Project: ignite   Source File: CacheHibernateBlobStoreSelfTest.java    License: 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 5
Source Project: ignite   Source File: CacheHibernateBlobStoreSelfTest.java    License: 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 6
Source Project: kardio   Source File: DBQueryUtil.java    License: 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
@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 8
Source Project: kardio   Source File: DBQueryUtil.java    License: 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 9
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 10
/**
 * 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 11
@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 12
Source Project: tutorials   Source File: HibernateExceptionUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenDeletingADeletedObject_thenOptimisticLockException() {
    thrown.expect(isA(OptimisticLockException.class));
    thrown.expectMessage(
        "Batch update returned unexpected row count from update");
    thrown.expectCause(isA(StaleStateException.class));

    Session session = null;
    Transaction transaction = null;

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();

        Product product1 = new Product();
        product1.setId(12);
        product1.setName("Product 12");
        session.save(product1);
        transaction.commit();
        session.close();

        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        Product product2 = session.get(Product.class, 12);
        session.createNativeQuery("delete from Product where id=12")
            .executeUpdate();
        // We need to refresh to fix the error.
        // session.refresh(product2);
        session.delete(product2);
        transaction.commit();
    } catch (Exception e) {
        rollbackTransactionQuietly(transaction);
        throw (e);
    } finally {
        closeSessionQuietly(session);
    }
}
 
Example 13
@Override
public SbiMetaDocTabRel loadDocIdandTableId(Integer documentId, Integer tableId) throws EMFUserError {

	logger.debug("IN");

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

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

		// Criterion labelCriterrion1 = Expression.eq("datasetId",
		// datasetId);
		// Criterion labelCriterrion2 = Expression.eq("tableId", tableId);
		List<SbiMetaDocTabRel> relations = tmpSession.createCriteria(SbiMetaDocTabRel.class).add(Restrictions.eq("documentId", documentId))
				.add(Restrictions.eq("tableId", tableId)).list();
		toReturn = relations.get(0);
		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 14
Source Project: Hi-WAY   Source File: HiwayDB.java    License: Apache License 2.0 5 votes vote down vote up
public HiwayDB(String username, String password, String dbURL) {
	this.username = username;
	this.password = password;
	this.dbURL = dbURL;
	this.wfName = "";
	this.runIDat = "";

	this.config = "nix";

	dbSessionFactory = getSQLSession();
	dbSessionFactoryMessung = getSQLSessionMessung();

	Session session = dbSessionFactory.openSession();
	Transaction tx = null;

	try {
		tx = session.beginTransaction();

		dbVolume = (long) session.createCriteria(Workflowrun.class).setProjection(Projections.rowCount()).uniqueResult();

		tx.commit();
	} catch (RuntimeException e) {
		if (tx != null)
			tx.rollback();
		throw e; // or display error message
	} finally {
		if (session.isOpen()) {
			session.close();
		}

	}

}
 
Example 15
@Override
public void removeParameter(Integer id) throws EMFUserError {

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

		removeParameter(id, aSession);

		// commit all changes
		tx.commit();
	} catch (HibernateException he) {
		if (tx != null && tx.isActive())
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} catch (Exception ex) {
		if (tx != null && tx.isActive())
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
}
 
Example 16
@Test
public void testLoadSnomedCt() throws Exception {
    ourLog.info("TEST = testLoadSnomedCt()");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(bos);
    addEntry(zos, "/sct/", "sct2_Concept_Full_INT_20160131.txt");
    addEntry(zos, "/sct/", "sct2_Concept_Full-en_INT_20160131.txt");
    addEntry(zos, "/sct/", "sct2_Description_Full-en_INT_20160131.txt");
    addEntry(zos, "/sct/", "sct2_Identifier_Full_INT_20160131.txt");
    addEntry(zos, "/sct/", "sct2_Relationship_Full_INT_20160131.txt");
    addEntry(zos, "/sct/", "sct2_StatedRelationship_Full_INT_20160131.txt");
    addEntry(zos, "/sct/", "sct2_TextDefinition_Full-en_INT_20160131.txt");
    zos.close();

    ourLog.info("ZIP file has {} bytes", bos.toByteArray().length);

    RequestDetails details = mock(RequestDetails.class);
    when(codeSvc.findBySystem(CareConnectSystem.SNOMEDCT)).thenReturn(new CodeSystemEntity());
    when(codeSvc.getSession()).thenReturn(mock(Session.class));
    when(codeSvc.getTransaction(any())).thenReturn(mock(Transaction.class));

    mySvc.loadSnomedCt(list(bos.toByteArray()), details);

    verify(codeSvc).storeNewCodeSystemVersion( myCsvCaptor.capture(), any(RequestDetails.class));

    CodeSystemEntity csv = myCsvCaptor.getValue();
    TreeSet<String> allCodes = toCodes(csv, true);
    ourLog.info("TEST = testLoadSnomedCt() withChildren = " + allCodes.toString());

    assertThat(allCodes, hasItem("116680003"));
  //  assertThat(allCodes, not(containsInAnyOrder("207527008")));

    allCodes = toCodes(csv, false);
    ourLog.info("TEST = testLoadSnomedCt() noChildren = " +allCodes.toString());
    assertThat(allCodes, hasItem("126813005"));
}
 
Example 17
public void testQuerySubclassAttribute() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Person p = new Person();
	p.setName("Emmanuel");
	p.setSex('M');
	s.persist(p);
	Employee q = new Employee();
	q.setName("Steve");
	q.setSex('M');
	q.setTitle("Mr");
	q.setSalary( new BigDecimal(1000) );
	s.persist(q);

	List result = s.createQuery("from Person where salary > 100").list();
	assertEquals( result.size(), 1 );
	assertSame( result.get(0), q );

	result = s.createQuery("from Person where salary > 100 or name like 'E%'").list();
	assertEquals( result.size(), 2 );

	result = s.createCriteria(Person.class)
		.add( Property.forName("salary").gt( new BigDecimal(100) ) )
		.list();
	assertEquals( result.size(), 1 );
	assertSame( result.get(0), q );

	//TODO: make this work:
	/*result = s.createQuery("select salary from Person where salary > 100").list();
	assertEquals( result.size(), 1 );
	assertEquals( result.get(0), new BigDecimal(1000) );*/

	s.delete(p);
	s.delete(q);
	t.commit();
	s.close();
}
 
Example 18
public void testQuery() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	s.createQuery("from LineItem ol where ol.order.id.customerId = 'C111'").list();
	t.commit();
	s.close();
}
 
Example 19
private void initData() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Componentizable master = getMaster("hibernate", "ORM tool", "ORM tool1");
    s.saveOrUpdate(master);
    master = getMaster("hibernate", "open source", "open source1");
    s.saveOrUpdate(master);
    master = getMaster("hibernate", null, null);
    s.saveOrUpdate(master);
    t.commit();
    s.close();
}
 
Example 20
Source Project: tp_java_2015_02   Source File: DBServiceImpl.java    License: MIT License 5 votes vote down vote up
public void save(UserDataSet dataSet) {
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    UserDataSetDAO dao = new UserDataSetDAO(session);
    dao.save(dataSet);
    transaction.commit();
}
 
Example 21
Source Project: modeldb   Source File: DatasetDAORdbImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Dataset addDatasetTags(String datasetId, List<String> tagsList)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    DatasetEntity datasetObj = session.get(DatasetEntity.class, datasetId);
    if (datasetObj == null) {
      String errorMessage = "Dataset not found for given ID";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    List<String> newTags = new ArrayList<>();
    Dataset existingProtoDatasetObj = datasetObj.getProtoObject();
    for (String tag : tagsList) {
      if (!existingProtoDatasetObj.getTagsList().contains(tag)) {
        newTags.add(tag);
      }
    }
    if (!newTags.isEmpty()) {
      List<TagsMapping> newTagMappings =
          RdbmsUtils.convertTagListFromTagMappingList(datasetObj, newTags);
      datasetObj.getTags().addAll(newTagMappings);
      datasetObj.setTime_updated(Calendar.getInstance().getTimeInMillis());
      Transaction transaction = session.beginTransaction();
      session.saveOrUpdate(datasetObj);
      transaction.commit();
    }
    LOGGER.debug("Dataset tags added successfully");
    return datasetObj.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return addDatasetTags(datasetId, tagsList);
    } else {
      throw ex;
    }
  }
}
 
Example 22
/**
 * 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 23
/**
 * Load all maps.
 *
 * @return the list
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.geo.bo.dao.IEngineDAO#loadAllEngines()
 */
@Override
public List loadAllMaps() throws EMFUserError {
	Session tmpSession = null;
	Transaction tx = null;
	List realResult = new ArrayList();
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		Query hibQuery = tmpSession.createQuery(" from SbiGeoMaps");

		List hibList = hibQuery.list();
		Iterator it = hibList.iterator();
		while (it.hasNext()) {
			SbiGeoMaps hibMap = (SbiGeoMaps) it.next();
			if (hibMap != null) {
				GeoMap biMap = hibMap.toGeoMap();
				realResult.add(biMap);
			}
		}
		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 24
/**
 * Gets the document labels list using parameter.
 *
 * @param parId
 *            the par id
 *
 * @return the document labels list using parameter
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IBIObjectParameterDAO#getDocumentLabelsListUsingParameter(java.lang.Integer)
 */
@Override
public List getDocumentLabelsListUsingParameter(Integer parId) throws HibernateException {

	List toReturn = new ArrayList();
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		String hql = "select " + "	distinct(obj.label) " + "from " + "	SbiObjects obj, SbiObjPar objPar " + "where "
				+ "	obj.biobjId = objPar.sbiObject.biobjId and " + "	objPar.sbiParameter.parId = " + parId;
		Query query = aSession.createQuery(hql);
		List result = query.list();

		toReturn = result;

		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 25
Source Project: kardio   Source File: TestDaoService.java    License: Apache License 2.0 5 votes vote down vote up
public ApiStatusEntity createApiStatusEntity(String envName) {
    // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    ApiStatusEntity apse = new ApiStatusEntity();
    Session session = sessionFactory.openSession();
    Transaction trx = session.beginTransaction();

    createEnvironment(envName, 0);
    EnvironmentEntity envEntity = envDao.getEnvironmentFromName(envName);

    createComponentType();
    createComponent();
    ComponentEntity parentComponentEntity = session.get(ComponentEntity.class, compID);
    createComponent();
    ComponentEntity componentEntity = session.get(ComponentEntity.class, compID);
    componentEntity.setParentComponent(parentComponentEntity);
    parentCompID++;
    session.save(componentEntity);

    apse.setEnvironment(envEntity);
    apse.setComponent(componentEntity);
    long date = System.currentTimeMillis();
    apse.setStatusDate(new java.sql.Date(date));
    apse.setDeltaValue(1);
    apse.setTotalApi(1);
    session.save(apse);
    apiStatusID++;
    trx.commit();
    session.close();
    return apse;

}
 
Example 26
public void testCollectionVersion() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Person gavin = new Person("Gavin");
	new Thing("Passport", gavin);
	s.persist(gavin);
	t.commit();
	s.close();
	
	assertEquals(0, gavin.getVersion());
	
	s = openSession();
	t = s.beginTransaction();
	gavin = (Person) s.createCriteria(Person.class).uniqueResult();
	new Thing("Laptop", gavin);
	t.commit();
	s.close();
	
	assertEquals(1, gavin.getVersion());
	assertFalse( Hibernate.isInitialized( gavin.getThings() ) );

	s = openSession();
	t = s.beginTransaction();
	gavin = (Person) s.createCriteria(Person.class).uniqueResult();
	gavin.getThings().clear();
	t.commit();
	s.close();
	
	assertEquals(2, gavin.getVersion());
	assertTrue( Hibernate.isInitialized( gavin.getThings() ) );

	s = openSession();
	t = s.beginTransaction();
	s.delete(gavin);
	t.commit();
	s.close();
}
 
Example 27
public void testQuerySubclassAttribute() {
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Person p = new Person();
	p.setName("Emmanuel");
	p.setSex('M');
	s.persist(p);
	Employee q = new Employee();
	q.setName("Steve");
	q.setSex('M');
	q.setTitle("Mr");
	q.setSalary( new BigDecimal(1000) );
	s.persist(q);

	List result = s.createQuery("from Person where salary > 100").list();
	assertEquals( result.size(), 1 );
	assertSame( result.get(0), q );

	result = s.createQuery("from Person where salary > 100 or name like 'E%'").list();
	assertEquals( result.size(), 2 );

	result = s.createCriteria(Person.class)
		.add( Property.forName("salary").gt( new BigDecimal(100) ) )
		.list();
	assertEquals( result.size(), 1 );
	assertSame( result.get(0), q );

	//TODO: make this work:
	/*result = s.createQuery("select salary from Person where salary > 100").list();
	assertEquals( result.size(), 1 );
	assertEquals( result.get(0), new BigDecimal(1000) );*/

	s.delete(p);
	s.delete(q);
	t.commit();
	s.close();
}
 
Example 28
@Override
public void insertDocRelation(SbiMetaDocTabRel sbiMetaDocTabRel) throws EMFUserError {
	logger.debug("IN");

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

		SbiMetaDocTabRel hibMeta = new SbiMetaDocTabRel();
		hibMeta.setDocumentId(sbiMetaDocTabRel.getDocumentId());
		hibMeta.setTableId(sbiMetaDocTabRel.getTableId());
		hibMeta.setRelationId(sbiMetaDocTabRel.getRelationId());

		updateSbiCommonInfo4Insert(hibMeta);
		tmpSession.save(hibMeta);
		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");
}
 
Example 29
public void testUnionSubclassCollection() {
	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);
	
	gavin.getInfo().put("foo", "bar");
	gavin.getInfo().put("x", "y");
	
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	gavin = (Human) s.createCriteria(Human.class).uniqueResult();
	assertEquals( gavin.getInfo().size(), 2 );
	s.delete(gavin);
	s.delete( gavin.getLocation() );
	t.commit();
	s.close();
}
 
Example 30
/**
 * Send message
 */
public static void send(String from, String to, String user, String subject, String content) throws
		DatabaseException {
	log.debug("send({}, {}, {}, {}, {})", new Object[]{from, to, user, subject, content});
	Session session = null;
	Transaction tx = null;

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

		MessageSent msgSent = new MessageSent();
		msgSent.setFrom(from);
		msgSent.setTo(to);
		msgSent.setUser(user);
		msgSent.setSubject(subject);
		msgSent.setContent(content);
		msgSent.setSentDate(Calendar.getInstance());
		session.save(msgSent);

		MessageReceived msgReceived = new MessageReceived();
		msgReceived.setFrom(from);
		msgReceived.setTo(to);
		msgReceived.setUser(user);
		msgReceived.setSubject(subject);
		msgReceived.setContent(content);
		msgReceived.setSentDate(Calendar.getInstance());
		session.save(msgReceived);

		HibernateUtil.commit(tx);
	} catch (HibernateException e) {
		HibernateUtil.rollback(tx);
		throw new DatabaseException(e.getMessage(), e);
	} finally {
		HibernateUtil.close(session);
	}

	log.debug("send: void");
}