Example usage for org.hibernate HibernateException HibernateException

List of usage examples for org.hibernate HibernateException HibernateException

Introduction

In this page you can find the example usage for org.hibernate HibernateException HibernateException.

Prototype

public HibernateException(Throwable cause) 

Source Link

Document

Constructs a HibernateException using the given message and underlying cause.

Usage

From source file:com.globalsight.persistence.hibernate.HibernateUtil.java

License:Apache License

/**
 * Return the persistent instance of the given entity class with the given
 * identifier, or null if there is no such persistent instance. (If the
 * instance is already associated with the session, return that instance.
 * This method never returns an uninitialized instance.)
 * //from   w w w. j  a v  a2  s .  c o m
 * @param clazz
 *            a persistent class
 * @param id
 *            an identifier
 * @return a persistent instance or null
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public static <T> T get(Class<T> clazz, Serializable id, boolean ignoreInActiveOb) throws HibernateException {
    T result = null;
    if (clazz != null) {
        Session session = null;
        try {
            session = getSession();
            result = (T) session.get(clazz, id);

            if (ignoreInActiveOb && result != null && isUseActive(result)) {
                Method method = result.getClass().getMethod("isActive");
                Boolean active = (Boolean) method.invoke(result, (Object[]) null);
                if (active != null && !active.booleanValue()) {
                    result = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new HibernateException(e);
        }
    }

    return result;
}

From source file:com.googlecode.hibernate.audit.extension.syncronization.DefaultTransactionSyncronization.java

License:Open Source License

private void checkForActiveTransaction(EventSource eventSource) {
    if (!eventSource.isTransactionInProgress()) {
        throw new HibernateException("No active transaction.");

    }//ww w  .j  a va2s  .  c  o m
}

From source file:com.googlecode.hibernate.audit.synchronization.work.AbstractAuditWorkUnit.java

License:Open Source License

protected AuditLogicalGroup getAuditLogicalGroup(Session session, AuditConfiguration auditConfiguration,
        AuditEvent auditEvent) {/*  w w  w  . jav  a  2s  . c o  m*/

    AuditLogicalGroup logicalGroup = auditConfiguration.getExtensionManager().getAuditLogicalGroupProvider()
            .getAuditLogicalGroup(session, auditEvent);

    AuditLogicalGroup result = null;

    if (logicalGroup != null) {
        AuditType auditType = HibernateAudit.getAuditType(session, logicalGroup.getAuditType().getClassName());
        String externalId = logicalGroup.getExternalId();

        result = HibernateAudit.getAuditLogicalGroup(session, auditType, externalId);

        HibernateException createAuditLogicalGroupException = null;
        if (result == null) {
            createAuditLogicalGroupException = createAuditLogicalGroup(session, logicalGroup, auditType);
            // remove the cached query (possibly null) results so that the result after that is not null. 
            NamedQueryDefinition namedQueryDefinition = ((SessionFactoryImplementor) session
                    .getSessionFactory()).getNamedQuery(
                            HibernateAudit.SELECT_AUDIT_LOCAL_GROUP_BY_AUDIT_TYPE_AND_EXTERNAL_ID);
            if (namedQueryDefinition.isCacheable()) {
                String cacheRegion = ((SessionFactoryImplementor) session.getSessionFactory())
                        .getNamedQuery(HibernateAudit.SELECT_AUDIT_LOCAL_GROUP_BY_AUDIT_TYPE_AND_EXTERNAL_ID)
                        .getCacheRegion();
                if (cacheRegion != null) {
                    session.getSessionFactory().getCache().evictQueryRegion(cacheRegion);
                } else {
                    session.getSessionFactory().getCache().evictQueryRegions();
                }
            }

            result = HibernateAudit.getAuditLogicalGroup(session, auditType, externalId);

        }
        if (result == null) {
            if (createAuditLogicalGroupException != null) {
                throw createAuditLogicalGroupException;
            } else {
                throw new HibernateException("Unable to create and then retrieve AuditLogicalGroup: className="
                        + logicalGroup.getAuditType().getClassName() + ",externalId="
                        + logicalGroup.getExternalId());
            }
        }
        auditLogicalGroups.add(result);
    }

    return result;
}

From source file:com.googlecode.hibernate.audit.synchronization.work.AbstractAuditWorkUnit.java

License:Open Source License

private HibernateException createAuditLogicalGroup(Session session, AuditLogicalGroup logicalGroup,
        AuditType auditType) {//from w  ww  . j  a  v a2s  .co  m
    Session newSession = null;

    TransactionManager txManager = null;
    javax.transaction.Transaction suspendedTransaction = null;

    try {
        JtaPlatform jtaPlatform = ((SessionFactoryImplementor) session.getSessionFactory()).getSettings()
                .getJtaPlatform();
        if (jtaPlatform != null) {
            txManager = jtaPlatform.retrieveTransactionManager();
        }

        if (txManager != null) {
            try {
                suspendedTransaction = txManager.suspend();
            } catch (SystemException e) {
                throw new HibernateException(e);
            }
        }
        Transaction tx = null;
        try {
            newSession = session.getSessionFactory().openSession();
            tx = newSession.beginTransaction();
            logicalGroup.setAuditType(auditType);
            // when we are creating the audit logical group for the first time we set it to 0, this is before even we may have transaction record - this is executed in separate transaction
            logicalGroup.setLastUpdatedAuditTransactionId(Long.valueOf(0));
            newSession.save(logicalGroup);
            tx.commit();

            return null;
        } catch (HibernateException e) {
            if (log.isDebugEnabled()) {
                // log the exception is debug level because this most likely
                // will indicate that there was a concurrent insert and we
                // are prepared to handle such calls. If this is not the
                // case and we want to troubleshoot where is the problem
                // then at least log the exception is DEBUG level so we can
                // see it.
                log.debug(
                        "HibernateException occured while creating a new AuditLogicalGroup in new transaction",
                        e);
            }
            if (tx != null) {
                try {
                    tx.rollback();
                } catch (HibernateException ignored) {
                }
            }

            return e;
        } finally {
            if (newSession != null && newSession.isOpen()) {
                try {
                    newSession.close();
                } catch (HibernateException ignored) {
                }
            }
        }
    } finally {
        if (txManager != null && suspendedTransaction != null) {
            try {
                txManager.resume(suspendedTransaction);
            } catch (SystemException e) {
                throw new HibernateException(e);
            } catch (InvalidTransactionException e) {
                throw new HibernateException(e);
            }
        }
    }
}

From source file:com.griffinslogistics.db.helpers.DeliveriesHelper.java

@Override
public boolean deleteDelivery(Delivery delivery) {
    logger.log(Level.SEVERE, "{0}: deleteDelivery started", CLASS_NAME);

    boolean isDeleted = false;

    this.session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();

    try {//  w  w  w.j  av  a  2s.  c  om
        this.session.delete(delivery);
        transaction.commit();
        isDeleted = true;
    } catch (HibernateException e) {
        transaction.rollback();
        DeliveriesHelper.logger.log(Level.SEVERE, e.getMessage(), delivery);
        throw new HibernateException(e);
    } finally {
        this.session.close();

        logger.log(Level.SEVERE, "{0}: deleteDelivery finished", CLASS_NAME);
    }

    return isDeleted;
}

From source file:com.gu.management.database.checking.SimpleConnectionCheckerTest.java

License:Apache License

@Test
public void testShouldFailWhenQueryExecutedOnStatementNotOk() throws Exception {
    Exception exception = new HibernateException(new SQLException("ORA-01089"));

    ConnectionChecker checker = new ConnectionCheckerBuilder().sqlQuery(sqlQuery).toConnectionChecker();
    when(sqlQuery.uniqueResult()).thenThrow(exception);

    ConnectionCheckResult result = checker.check();
    assertThat(result.isSuccessful(), equalTo(false));
    assertThat(result.getFailureCause(), equalTo(exception));
}

From source file:com.huntnet.conexion.Conexion.java

/**
 *
 * @param he/*from  w w w  .j  a  v a2 s .c o m*/
 */
public void catchException(HibernateException he) {
    if (this.getTransaction() != null && this.getTransaction().isActive()) {
        this.getTransaction().rollback();
    }
    throw new HibernateException(
            "[ERROR 1] Ocurri un error al acceder a la base de datos: " + he.getMessage());
}

From source file:com.hyzy.core.orm.hibernate.HibernateDao.java

License:Apache License

/**
* 
        //from   www. j  av  a 2s .  c  o m
*????
        
* @author: zhaozongzhan
        
* @create: 2016114 ?5:57:01
        
*
        
* @param showFieldNames
* @param queryFilters
* @return
*/
public T getAppointedFieldNamesByEntity(List<String> showFieldNames, List<PropertyFilter> queryFilters) {
    Criterion[] criterions = buildCriterionByPropertyFilter(queryFilters);
    if (showFieldNames == null || showFieldNames.size() <= 0) {

        return (T) findShowFieldsUniqueResult(showFieldNames, criterions);
    }
    Object o = findShowFieldsUniqueResult(showFieldNames, criterions);

    if (o != null) {
        T entity = null;
        try {
            entity = entityClass.newInstance();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("Could not instantiate entityClass: " + entityClass.getName());
            logger.error(String.format("getAppointedFieldNamesByEntity :%s:%",
                    entityClass.getName(), e.getMessage()));
            e.printStackTrace();
            throw new HibernateException("Could not instantiate entityClass: " + entityClass.getName());

        }
        setObjectValuesToEntity(o, entity, showFieldNames);
        return entity;
    } else
        return null;
}

From source file:com.hyzy.core.orm.hibernate.HibernateDao.java

License:Apache License

/**
 * // w ww.  jav a  2  s .  com
        
 *
        
 * @author: zhaozongzhan
        
 * @create: 2016112 ?5:27:29
        
 *
        
 * @param values ?
 * @param entitylist ?
 * @param showFieldNames  ?
 */

private void setArrayValuesToEntity(List values, List<T> entitylist, List<String> showFieldNames) {

    if (values != null && values.size() > 0) {

        if (showFieldNames != null && showFieldNames.size() > 0) {
            int showFieldNamesSize = showFieldNames.size();
            List<T> myentitys = new ArrayList();
            for (int i = 0; i < values.size(); i++) {
                T entity = null;
                try {
                    entity = entityClass.newInstance();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    logger.error("Could not instantiate entityClass: " + entityClass.getName());
                    logger.error(String.format("getAppointedFieldNamesByEntity :%s:%",
                            entityClass.getName(), e.getMessage()));
                    e.printStackTrace();
                    throw new HibernateException("Could not instantiate entityClass: " + entityClass.getName());

                }
                //??HIBERNATE?????
                if (showFieldNamesSize > 1) {
                    Object[] fieldValueArry = (Object[]) values.get(i);

                    int fieldSize = fieldValueArry.length;

                    for (int f = 0; f < fieldSize; f++) {
                        ClassUtils.setFieldValue(entity, showFieldNames.get(f), fieldValueArry[f]);
                    }

                } else {
                    Object fieldValueObj = values.get(i);
                    ClassUtils.setFieldValue(entity, showFieldNames.get(0), fieldValueObj);
                }
                entitylist.add(entity);
            }

        } else {
            entitylist.addAll(values);
        }

    }

}

From source file:com.infinities.keystone4j.jpa.provider.BoneCPConnectionProvider.java

License:Apache License

/**
 * Creates the given connection pool with the given configuration. Extracted
 * here to make unit mocking easier.//from ww  w  . j  ava2 s .c o  m
 * 
 * @param config
 *            configuration object.
 * @return BoneCP connection pool handle.
 */
protected BoneCP createPool(BoneCPConfig config) {
    try {
        return new BoneCP(config);
    } catch (SQLException e) {
        throw new HibernateException(e);
    }
}