List of usage examples for org.hibernate SQLQuery uniqueResult
R uniqueResult();
From source file:com.connexience.server.model.datasets.DatasetsUtils.java
License:Open Source License
/** Get the size of a multiple json value item */ public static int getJsonMultipleValueDataSize(Session session, JsonMultipleValueItem item) throws ConnexienceException { SQLQuery q = session.createSQLQuery("select count(id) from datasetjson where itemid=:itemid"); q.setLong("itemid", item.getId()); //q.addEntity(Long.class); return ((Number) q.uniqueResult()).intValue(); }
From source file:com.corundumstudio.core.extensions.hibernate.InsertDeleteUniqueResultTest.java
License:Apache License
private void checkQueryResult(SimpleEntity entity, Long expected) { Session session = sessionFactory.openSession(); SQLQuery query = session.createSQLQuery("SELECT id FROM SimpleEntity WHERE phone = :phone"); query.addScalar("id", LongType.INSTANCE); query.setCacheable(true);// w w w. ja va 2s.co m query.setCacheRegion(cacheRegion); query.setParameter("phone", entity.getPhone()); Long res = (Long) query.uniqueResult(); Assert.assertEquals(expected, res); session.close(); }
From source file:com.daro.persistence.generic.dao.GenericDaoImpl.java
License:GNU General Public License
/** * Get Entity T using a SQL query string and SqlQuery object. * // w ww . j ava2s . com * @param sql * @return * @throws PersistenceException */ @SuppressWarnings("unchecked") public T executeSqlQuery(String sql) throws PersistenceException { T t = null; SQLQuery query = createSqlQuery(sql); try { query.addEntity(clazz); t = (T) query.uniqueResult(); } catch (Exception e) { throw new PersistenceException(e); } return t; }
From source file:com.daro.persistence.generic.dao.GenericDaoImpl.java
License:GNU General Public License
/** * Get Entity T using a SQL query string and SqlQuery object with parameters list. * /*from ww w . j a v a 2 s . c o m*/ * @param sql For example "SELECT * FROM table WHERE id = ?" * @param params Parameters list to match with ? in SQL query * @return Entity T type * @throws PersistenceException */ @SuppressWarnings("unchecked") public T executeSqlQuery(String sql, List<String> params) throws PersistenceException { T t = null; SQLQuery query = createSqlQuery(sql); try { query.addEntity(clazz); //inserts parameters into sql string replacing ? symbols by order for (int i = 0; i < params.size(); i++) { query.setParameter(i, params.get(i)); } t = (T) query.uniqueResult(); } catch (Exception e) { throw new PersistenceException(e); } return t; }
From source file:com.dell.asm.asmcore.asmmanager.db.DeviceGroupDAO.java
License:Open Source License
/** * Returns the number of servers available in the pool. * //from w w w .j a v a 2s . co m * @param poolId the id of the pool whose server count will be returned. * @return the number of servers available in the pool. */ public int getNumberOfServersInPool(final String poolId) { int numberOfServersInPool = 0; if (poolId != null && poolId.trim().length() > 0) { // Initialize locals. Session session = null; Transaction tx = null; try { session = _dao._database.getNewSession(); tx = session.beginTransaction(); SQLQuery query = session.createSQLQuery(POOL_SERVERS_COUNT); query.setParameter("poolId", Long.valueOf(poolId)); numberOfServersInPool = ((BigInteger) query.uniqueResult()).intValue(); tx.commit(); } catch (Exception e) { logger.warn("Caught exception during getNumberOfServersInPool: " + e); try { if (tx != null) { tx.rollback(); } } catch (Exception ex) { logger.warn("Unable to rollback transaction during getNumberOfServersInPool: " + ex); } } finally { try { if (session != null) { session.close(); } } catch (Exception ex) { logger.warn("Unable to close session during getNumberOfServersInPool: " + ex); } } } return numberOfServersInPool; }
From source file:com.emergya.persistenceGeo.dao.impl.PostgisDBManagementDaoHibernateImpl.java
License:Open Source License
/** * Gets a postgis table geometry type.//from w ww.j a v a 2 s .com * * @param tableName * @return */ @Override public GeometryType getTableGeometryType(String tableName) { SQLQuery query = getSession().createSQLQuery(GEOMETRY_TYPE_SQL); query.setString("NAME", tableName); String dbType = ((String) query.uniqueResult()).toUpperCase(); if (StringUtils.contains(dbType, "POINT")) { return GeometryType.POINT; } else if (StringUtils.contains(dbType, "LINE")) { return GeometryType.LINESTRING; } else if (StringUtils.contains(dbType, "POLYGON")) { return GeometryType.POLYGON; } else { throw new IllegalStateException( String.format("Type %s is not a PersistenceGeo supported GeometryType.", dbType)); } }
From source file:com.emergya.persistenceGeo.dao.impl.PostgisDBManagementDaoHibernateImpl.java
License:Open Source License
private BoundingBox calculateBBox(String sql, String tableName) { SQLQuery query = getSession().createSQLQuery(sql); String result = (String) query.uniqueResult(); BoundingBox bbox = new BoundingBox(); if (result == null) { // if layer is empty bbox.setMinx(-180);//from w w w. j av a2 s .co m bbox.setMiny(-90); bbox.setMaxx(180); bbox.setMaxy(90); } else { result = result.replace("BOX", ""); result = result.replace("(", "").replace(")", ""); result = result.replace(" ", ","); String[] coords = result.split(","); if (coords[0].equals(coords[2]) && coords[1].equals(coords[3])) { // layer // store // one // point bbox.setMinx((Double.valueOf(coords[0]) / 2) - 0.75); bbox.setMiny((Double.valueOf(coords[1]) / 2) - 0.75); bbox.setMaxx((Double.valueOf(coords[2]) / 2) + 0.75); bbox.setMaxy((Double.valueOf(coords[3]) / 2) + 0.75); } else { bbox.setMinx(Double.valueOf(coords[0])); bbox.setMiny(Double.valueOf(coords[1])); bbox.setMaxx(Double.valueOf(coords[2])); bbox.setMaxy(Double.valueOf(coords[3])); } } query = getSession().createSQLQuery(SRID_SQL); query.setString("NAME", tableName); Integer srid = (Integer) query.uniqueResult(); bbox.setSrs("EPSG:" + srid); return bbox; }
From source file:com.emergya.persistenceGeo.dao.impl.PostgisDBManagementDaoHibernateImpl.java
License:Open Source License
@Override public boolean tableExists(String schema, String tableName) { String sql = "select * from pg_tables where schemaname='" + schema + "' and tablename = '" + tableName + "';"; SQLQuery query = getSession().createSQLQuery(sql); return query.uniqueResult() != null; }
From source file:com.evolveum.midpoint.repo.sql.DeleteTest.java
License:Apache License
@Test public void delete0003() throws Exception { PrismObject<ShadowType> shadow = prismContext.parseObject(new File(FOLDER_BASE, "delete/shadow.xml")); OperationResult result = new OperationResult("add shadow"); final String oid = repositoryService.addObject(shadow, null, result); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, oid, null, result); shadow = prismContext.parseObject(new File(FOLDER_BASE, "delete/shadow.xml")); AssertJUnit.assertEquals(shadow, repoShadow); repositoryService.deleteObject(ShadowType.class, oid, result); result.recomputeStatus();/*from ww w . j a v a2 s.c o m*/ AssertJUnit.assertTrue(result.isSuccess()); Session session = getFactory().openSession(); try { SQLQuery query = session.createSQLQuery("select count(*) from m_trigger where owner_oid = ?"); query.setString(0, oid); Number count = (Number) query.uniqueResult(); AssertJUnit.assertEquals(count.longValue(), 0L); } finally { session.close(); } }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
License:Apache License
public <T extends ObjectType> PrismObject<T> getObjectInternal(Session session, Class<T> type, String oid, Collection<SelectorOptions<GetOperationOptions>> options, boolean lockForUpdate, OperationResult operationResult) throws ObjectNotFoundException, SchemaException, DtoTranslationException { boolean lockedForUpdateViaHibernate = false; boolean lockedForUpdateViaSql = false; LockOptions lockOptions = new LockOptions(); //todo fix lock for update!!!!! if (lockForUpdate) { if (getConfiguration().isLockForUpdateViaHibernate()) { lockOptions.setLockMode(LockMode.PESSIMISTIC_WRITE); lockedForUpdateViaHibernate = true; } else if (getConfiguration().isLockForUpdateViaSql()) { LOGGER.trace("Trying to lock object {} for update (via SQL)", oid); long time = System.currentTimeMillis(); SQLQuery q = session.createSQLQuery("select oid from m_object where oid = ? for update"); q.setString(0, oid);// w w w .jav a 2 s .c o m Object result = q.uniqueResult(); if (result == null) { return throwObjectNotFoundException(type, oid); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Locked via SQL (in {} ms)", System.currentTimeMillis() - time); } lockedForUpdateViaSql = true; } } if (LOGGER.isTraceEnabled()) { if (lockedForUpdateViaHibernate) { LOGGER.trace("Getting object {} with locking for update (via hibernate)", oid); } else if (lockedForUpdateViaSql) { LOGGER.trace("Getting object {}, already locked for update (via SQL)", oid); } else { LOGGER.trace("Getting object {} without locking for update", oid); } } GetObjectResult fullObject = null; if (!lockForUpdate) { Query query = session.getNamedQuery("get.object"); query.setString("oid", oid); query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER); query.setLockOptions(lockOptions); fullObject = (GetObjectResult) query.uniqueResult(); } else { // we're doing update after this get, therefore we load full object right now // (it would be loaded during merge anyway) // this just loads object to hibernate session, probably will be removed later. Merge after this get // will be faster. Read and use object only from fullObject column. // todo remove this later [lazyman] Criteria criteria = session.createCriteria(ClassMapper.getHQLTypeClass(type)); criteria.add(Restrictions.eq("oid", oid)); criteria.setLockMode(lockOptions.getLockMode()); RObject obj = (RObject) criteria.uniqueResult(); if (obj != null) { obj.toJAXB(prismContext, null).asPrismObject(); fullObject = new GetObjectResult(obj.getFullObject(), obj.getStringsCount(), obj.getLongsCount(), obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount(), obj.getBooleansCount()); } } LOGGER.trace("Got it."); if (fullObject == null) { throwObjectNotFoundException(type, oid); } LOGGER.trace("Transforming data to JAXB type."); PrismObject<T> prismObject = updateLoadedObject(fullObject, type, oid, options, session, operationResult); validateObjectType(prismObject, type); // this was implemented to allow report parsing errors as warnings to upper layers; // however, it causes problems when serialization problems are encountered: in such cases, we put // FATAL_ERROR to the result here, and it should be then removed or muted (which is a complication) // -- so, as the parsing errors are not implemented, we disabled this code as well // subResult.computeStatusIfUnknown(); // if (subResult.isWarning() || subResult.isError() || subResult.isInProgress()) { // prismObject.asObjectable().setFetchResult(subResult.createOperationResultType()); // } return prismObject; }