org.hibernate.HibernateException Java Examples
The following examples show how to use
org.hibernate.HibernateException.
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: Route.java From core with GNU General Public License v3.0 | 6 votes |
/** * Returns List of Route objects for the specified database revision. * Orders them based on the GTFS route_order extension or the * route short name if route_order not set. * * @param session * @param configRev * @return Map of routes keyed on routeId * @throws HibernateException */ @SuppressWarnings("unchecked") public static List<Route> getRoutes(Session session, int configRev) throws HibernateException { // Get list of routes from database String hql = "FROM Route " + " WHERE configRev = :configRev" + " ORDER BY routeOrder, shortName"; Query query = session.createQuery(hql); query.setInteger("configRev", configRev); List<Route> routesList = query.list(); // Need to set the route order for each route so that can sort // predictions based on distance from stop and route order. For // the routes that didn't have route ordered configured in db // start with 1000 and count on up. int routeOrderForWhenNotConfigured = 1000; for (Route route: routesList) { if (!route.atBeginning() && !route.atEnd()) { route.setRouteOrder(routeOrderForWhenNotConfigured++); } } // Return the list of routes return routesList; }
Example #2
Source File: EntityType.java From lams with GNU General Public License v2.0 | 6 votes |
protected final Object getIdentifier(Object value, SharedSessionContractImplementor session) throws HibernateException { if ( isReferenceToPrimaryKey() || uniqueKeyPropertyName == null ) { return ForeignKeys.getEntityIdentifierIfNotUnsaved( getAssociatedEntityName(), value, session ); //tolerates nulls } else if ( value == null ) { return null; } else { EntityPersister entityPersister = getAssociatedEntityPersister( session.getFactory() ); Object propertyValue = entityPersister.getPropertyValue( value, uniqueKeyPropertyName ); // We now have the value of the property-ref we reference. However, // we need to dig a little deeper, as that property might also be // an entity type, in which case we need to resolve its identitifier Type type = entityPersister.getPropertyType( uniqueKeyPropertyName ); if ( type.isEntityType() ) { propertyValue = ( (EntityType) type ).getIdentifier( propertyValue, session ); } return propertyValue; } }
Example #3
Source File: CacheEntry.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
public CacheEntry( final Object[] state, final EntityPersister persister, final boolean unfetched, final Object version, final SessionImplementor session, final Object owner) throws HibernateException { //disassembled state gets put in a new array (we write to cache by value!) this.disassembledState = TypeFactory.disassemble( state, persister.getPropertyTypes(), persister.isLazyPropertiesCacheable() ? null : persister.getPropertyLaziness(), session, owner ); subclass = persister.getEntityName(); lazyPropertiesAreUnfetched = unfetched || !persister.isLazyPropertiesCacheable(); this.version = version; }
Example #4
Source File: WikiPageDAO.java From document-management-system with GNU General Public License v2.0 | 6 votes |
/** * Create */ public static long create(WikiPage wkp) throws DatabaseException { log.debug("create({})", wkp); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); Long id = (Long) session.save(wkp); HibernateUtil.commit(tx); log.debug("create: {}" + id); return id; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } }
Example #5
Source File: DBManager.java From olat with Apache License 2.0 | 6 votes |
int delete(String query, Object value, Type type) { int deleted = 0; try { // old: deleted = getSession().delete(query, value, type); Session si = getSession(); Query qu = si.createQuery(query); qu.setParameter(0, value, type); List foundToDel = qu.list(); int deletionCount = foundToDel.size(); for (int i = 0; i < deletionCount; i++) { si.delete(foundToDel.get(i)); } // // getSession().flush(); if (log.isDebugEnabled()) { logQuery("delete", new Object[] { value }, new Type[] { type }, query); } } catch (HibernateException e) { setError(e); throw new DBRuntimeException("Delete error. Query" + query + " Object: " + value, e); } return deleted; }
Example #6
Source File: BaseHibernateManager.java From sakai with Educational Community License v2.0 | 6 votes |
protected void updateAssignment(final GradebookAssignment assignment) throws ConflictingAssignmentNameException, HibernateException { // Ensure that we don't have the assignment in the session, since // we need to compare the existing one in the db to our edited assignment final Session session = getSessionFactory().getCurrentSession(); session.evict(assignment); final GradebookAssignment asnFromDb = (GradebookAssignment) session.load(GradebookAssignment.class, assignment.getId()); final Long count = (Long) session.createCriteria(GradableObject.class) .add(Restrictions.eq("name", assignment.getName())) .add(Restrictions.eq("gradebook", assignment.getGradebook())) .add(Restrictions.ne("id", assignment.getId())) .add(Restrictions.eq("removed", false)) .setProjection(Projections.rowCount()) .uniqueResult(); if(count > 0) { throw new ConflictingAssignmentNameException("You can not save multiple assignments in a gradebook with the same name"); } session.evict(asnFromDb); session.update(assignment); }
Example #7
Source File: DataDbLogger.java From core with GNU General Public License v3.0 | 6 votes |
/** * 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 #8
Source File: BusinessModelVisualDependenciesResource.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
@POST @Consumes("application/json") @Produces("application/json") public MetaModelParview addVisualDependeciesForBusinessModelDriver(@PathParam("id") Integer id, MetaModelParview parameterViewObject) { logger.debug("IN"); IMetaModelParviewDAO parameterViewDAO; Integer newId = null; Assert.assertNotNull(parameterViewObject, "Visual Dependencies can not be null"); try { parameterViewDAO = DAOFactory.getMetaModelParviewDao(); newId = parameterViewDAO.insertMetaModelParview(parameterViewObject); parameterViewObject.setId(newId); } catch (HibernateException e) { logger.error("Visual Dependencies can not be created", e); throw new SpagoBIRestServiceException(e.getCause().getLocalizedMessage() + "in Visual Dependencsies", buildLocaleFromSession(), e); } logger.debug("OUT"); return parameterViewObject; }
Example #9
Source File: AbstractPersistentCollection.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
static void identityRemove( Collection list, Object object, String entityName, SessionImplementor session) throws HibernateException { if ( object!=null && ForeignKeys.isNotTransient(entityName, object, null, session) ) { Type idType = session.getFactory().getEntityPersister(entityName).getIdentifierType(); Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, object, session); Iterator iter = list.iterator(); while ( iter.hasNext() ) { Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, iter.next(), session); if ( idType.isEqual( idOfCurrent, idOfOld, session.getEntityMode(), session.getFactory() ) ) { iter.remove(); break; } } } }
Example #10
Source File: ObjTemplate.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
/** * Tries to load binary content from database for this ObjTemplate instance, given its binary content identifier, if content field is null. * * @return The binary content of this instance; if it is null, it tries to load it from database if binary content identifier is available * * @throws EMFUserError * if some errors while reading from db occurs * @throws EMFInternalError * if some errors while reading from db occurs */ public byte[] getContent() throws HibernateException { if (content == null) { if (binId != null) { // reads from database try { content = DAOFactory.getBinContentDAO().getBinContent(binId); } catch (HibernateException e) { logger.error("Error while recovering content of template with id = [" + id + "], binary content id = [" + binId + "], " + "name = [" + name + "] of biobject with id = [" + biobjId + "]" + e); throw new HibernateException(e.getLocalizedMessage(), e); } } else { logger.warn("Both content field of this istance and binary identifier are null. Cannot load content from database."); } } return content; }
Example #11
Source File: HibernateTemplate.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public <T> T get(final Class<T> entityClass, final Serializable id, final LockMode lockMode) throws DataAccessException { return executeWithNativeSession(new HibernateCallback<T>() { @Override @SuppressWarnings("unchecked") public T doInHibernate(Session session) throws HibernateException { if (lockMode != null) { return (T) session.get(entityClass, id, lockMode); } else { return (T) session.get(entityClass, id); } } }); }
Example #12
Source File: ActivityDAO.java From document-management-system with GNU General Public License v2.0 | 6 votes |
/** * Create activity */ public static void create(Activity activity) throws DatabaseException { Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); session.save(activity); HibernateUtil.commit(tx); } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } }
Example #13
Source File: Constraint.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Hash a constraint name using MD5. Convert the MD5 digest to base 35 * (full alphanumeric), guaranteeing * that the length of the name will always be smaller than the 30 * character identifier restriction enforced by a few dialects. * * @param s * The name to be hashed. * @return String The hased name. */ public static String hashedName(String s) { try { MessageDigest md = MessageDigest.getInstance( "MD5" ); md.reset(); md.update( s.getBytes() ); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger( 1, digest ); // By converting to base 35 (full alphanumeric), we guarantee // that the length of the name will always be smaller than the 30 // character identifier restriction enforced by a few dialects. return bigInt.toString( 35 ); } catch ( NoSuchAlgorithmException e ) { throw new HibernateException( "Unable to generate a hashed Constraint name!", e ); } }
Example #14
Source File: CourseManagementAdministrationHibernateImpl.java From sakai with Educational Community License v2.0 | 6 votes |
private MembershipCmImpl getMembership(final String userId, final AbstractMembershipContainerCmImpl container) { final String lcUserId = StringUtils.lowerCase(userId); // This may be a dynamic proxy. In that case, make sure we're using the class // that hibernate understands. final String className = Hibernate.getClass(container).getName(); final StringBuilder sb = new StringBuilder("select mbr from MembershipCmImpl as mbr, "); sb.append(className); sb.append(" as container where mbr.memberContainer=container "); sb.append("and container.eid=:eid "); sb.append("and mbr.userId=:userId"); HibernateCallback hc = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query q = session.createQuery(sb.toString()); q.setParameter("eid", container.getEid()); q.setParameter("userId", lcUserId); return q.uniqueResult(); } }; return (MembershipCmImpl)getHibernateTemplate().execute(hc); }
Example #15
Source File: HQLQueryPlan.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
public ScrollableResults performScroll( QueryParameters queryParameters, SessionImplementor session) throws HibernateException { if ( log.isTraceEnabled() ) { log.trace( "iterate: " + getSourceQuery() ); queryParameters.traceParameters( session.getFactory() ); } if ( translators.length != 1 ) { throw new QueryException( "implicit polymorphism not supported for scroll() queries" ); } if ( queryParameters.getRowSelection().definesLimits() && translators[0].containsCollectionFetches() ) { throw new QueryException( "firstResult/maxResults not supported in conjunction with scroll() of a query containing collection fetches" ); } return translators[0].scroll( queryParameters, session ); }
Example #16
Source File: SerializableType.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public boolean isEqual(Object x, Object y) throws HibernateException { if ( x == y ) { return true; } if ( x == null || y == null ) { return false; } return x.equals( y ) || Hibernate.BINARY.isEqual( toBytes( x ), toBytes( y ) ); }
Example #17
Source File: MessageDaoImpl.java From sakai with Educational Community License v2.0 | 5 votes |
public List findBySpace(final String pageSpace) { long start = System.currentTimeMillis(); try { // there is no point in sorting by version, since there is only one // version in // this table. // also using like is much slower than eq HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { return session.createCriteria(Message.class).add( Expression.eq("pagespace", pageSpace)).list(); } }; return (List) getHibernateTemplate().execute(callback); } finally { long finish = System.currentTimeMillis(); TimeLogger.printTimer("PagePresenceDaoImpl.findBySpace: " + pageSpace, start, finish); } }
Example #18
Source File: SchemaExport.java From projectforge-webapp with GNU General Public License v3.0 | 5 votes |
/** Updates the current DB-Schema with the schema defined by the hbm.xml files. * * @param script Print the DDL to the console. * @param export */ public void updateSchema(Configuration cfg, boolean script, boolean export) { try { SchemaUpdate exp = new SchemaUpdate(cfg); exp.execute(script, export); } catch (HibernateException ex) { log.fatal("Cant't update database schema: " + ex.getMessage(), ex); return; } }
Example #19
Source File: GradebookServiceHibernateImpl.java From sakai with Educational Community License v2.0 | 5 votes |
private List<GradebookAssignment> getAssignmentsCounted(final Long gradebookId) throws HibernateException { final HibernateCallback<List<GradebookAssignment>> hc = session -> session .createQuery( "from GradebookAssignment as asn where asn.gradebook.id = :gradebookid and asn.removed is false and asn.notCounted is false") .setLong("gradebookid", gradebookId) .list(); return getHibernateTemplate().execute(hc); }
Example #20
Source File: AbstractCollectionPersister.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void processQueuedOps(PersistentCollection collection, Serializable key, SharedSessionContractImplementor session) throws HibernateException { if ( collection.hasQueuedOperations() ) { doProcessQueuedOps( collection, key, session ); } }
Example #21
Source File: ScrollableResultsImpl.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * @see org.hibernate.ScrollableResults#afterLast() */ public void afterLast() throws HibernateException { try { getResultSet().afterLast(); } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( getSession().getFactory().getSQLExceptionConverter(), sqle, "exception calling afterLast()" ); } }
Example #22
Source File: MessageDAO.java From document-management-system with GNU General Public License v2.0 | 5 votes |
/** * 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"); }
Example #23
Source File: SubqueryExpression.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { final SessionImplementor session = ( (CriteriaImpl) criteria ).getSession(); //ugly! final SessionFactoryImplementor factory = session.getFactory(); final OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister( criteriaImpl.getEntityOrClassName() ); CriteriaQueryTranslator innerQuery = new CriteriaQueryTranslator( factory, criteriaImpl, criteriaImpl.getEntityOrClassName(), //implicit polymorphism not supported (would need a union) criteriaQuery.generateSQLAlias(), criteriaQuery ); params = innerQuery.getQueryParameters(); //TODO: bad lifecycle.... types = innerQuery.getProjectedTypes(); //String filter = persister.filterFragment( innerQuery.getRootSQLALias(), session.getEnabledFilters() ); String sql = new Select( factory.getDialect() ) .setWhereClause( innerQuery.getWhereCondition() ) .setGroupByClause( innerQuery.getGroupBy() ) .setSelectClause( innerQuery.getSelect() ) .setFromClause( persister.fromTableFragment( innerQuery.getRootSQLALias() ) + persister.fromJoinFragment( innerQuery.getRootSQLALias(), true, false ) ) .toStatementString(); final StringBuffer buf = new StringBuffer() .append( toLeftSqlString(criteria, criteriaQuery) ); if (op!=null) buf.append(' ').append(op).append(' '); if (quantifier!=null) buf.append(quantifier).append(' '); return buf.append('(').append(sql).append(')') .toString(); }
Example #24
Source File: HibernateInterceptorTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testInterceptorWithNewSession() throws HibernateException { HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setSessionFactory(sessionFactory); try { interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } verify(session).flush(); verify(session).close(); }
Example #25
Source File: ObjParviewDAOHibImpl.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
/** * Erase obj parview. * * @param aObjParview the a obj parview * * @throws EMFUserError the EMF user error * * @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IObjParviewDAO#eraseObjParview(ObjParview) */ @Override public void eraseObjParview(ObjParview aObjParview) throws HibernateException { Session aSession = null; Transaction tx = null; try { aSession = getSession(); tx = aSession.beginTransaction(); eraseObjParview(aObjParview, aSession); 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(); } } /* * Criterion aCriterion = Expression.and( Expression.eq("id.sbiObjPar.objParId", aObjParuse.getObjParId()), Expression.eq("id.sbiParuse.useId", * aObjParuse.getParuseId())); Criteria aCriteria = aSession.createCriteria(SbiObjParuse.class); aCriteria.add(aCriterion); SbiObjParuse sbiObjParuse = * (SbiObjParuse)aCriteria.uniqueResult(); */ }
Example #26
Source File: DefaultLockEventListener.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Handle the given lock event. * * @param event The lock event to be handled. * @throws HibernateException */ public void onLock(LockEvent event) throws HibernateException { if ( event.getObject() == null ) { throw new NullPointerException( "attempted to lock null" ); } if ( event.getLockMode() == LockMode.WRITE ) { throw new HibernateException( "Invalid lock mode for lock()" ); } if ( event.getLockMode() == LockMode.UPGRADE_SKIPLOCKED ) { LOG.explicitSkipLockedLockCombo(); } SessionImplementor source = event.getSession(); Object entity = source.getPersistenceContext().unproxyAndReassociate( event.getObject() ); //TODO: if object was an uninitialized proxy, this is inefficient, // resulting in two SQL selects EntityEntry entry = source.getPersistenceContext().getEntry(entity); if (entry==null) { final EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity ); final Serializable id = persister.getIdentifier( entity, source ); if ( !ForeignKeys.isNotTransient( event.getEntityName(), entity, Boolean.FALSE, source ) ) { throw new TransientObjectException( "cannot lock an unsaved transient instance: " + persister.getEntityName() ); } entry = reassociate(event, entity, id, persister); cascadeOnLock(event, persister, entity); } upgradeLock( entity, entry, event.getLockOptions(), event.getSession() ); }
Example #27
Source File: ProgressThreadDAOImpl.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
@Override public ProgressThread loadActiveProgressThreadByUserIdAndFuncCd(String userId, String functCd) throws EMFUserError { // logger.debug("IN"); 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.functionCd = ? AND (h.status = '" + STARTED + "' OR h.status ='" + PREPARED + "') "); hibPT.setString(0, userId); hibPT.setString(1, functCd); SbiProgressThread sbiProgressThread = (SbiProgressThread) hibPT.uniqueResult(); if (sbiProgressThread != null) { toReturn = toProgressThread(sbiProgressThread); } tx.commit(); } catch (HibernateException he) { logger.error("Error while loading Progress Thread with progresThreadId", 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 #28
Source File: PostgreSQLEnumType.java From hibernate-types with Apache License 2.0 | 5 votes |
public void nullSafeSet( PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { st.setObject(index, value != null ? ((Enum) value).name() : null, Types.OTHER); }
Example #29
Source File: IgniteStandardQueryCacheFactory.java From sakai with Educational Community License v2.0 | 5 votes |
@Override public QueryCache getQueryCache( final String regionName, final UpdateTimestampsCache updateTimestampsCache, final Settings settings, final Properties props) throws HibernateException { return new IgniteStandardQueryCache(settings, props, updateTimestampsCache, regionName); }
Example #30
Source File: SessionFactoryImpl.java From lams with GNU General Public License v2.0 | 5 votes |
private Object instantiate(String listenerImpl, ClassLoaderService classLoaderService) { try { return classLoaderService.classForName( listenerImpl ).newInstance(); } catch (Exception e) { throw new HibernateException( "Could not instantiate requested listener [" + listenerImpl + "]", e ); } }