Search in sources :

Example 1 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project hibernate-orm by hibernate.

the class ExceptionTest method testConstraintViolationException.

@Test
public void testConstraintViolationException() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Music music = new Music();
    music.setName("Jazz");
    em.persist(music);
    Musician lui = new Musician();
    lui.setName("Lui Armstrong");
    lui.setFavouriteMusic(music);
    em.persist(lui);
    em.getTransaction().commit();
    try {
        em.getTransaction().begin();
        String hqlDelete = "delete Music where name = :name";
        em.createQuery(hqlDelete).setParameter("name", "Jazz").executeUpdate();
        em.getTransaction().commit();
        fail();
    } catch (PersistenceException e) {
        Throwable t = e.getCause();
        assertTrue("Should be a constraint violation", t instanceof ConstraintViolationException);
        em.getTransaction().rollback();
    } finally {
        em.close();
    }
}
Also used : EntityManager(javax.persistence.EntityManager) PersistenceException(javax.persistence.PersistenceException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) Test(org.junit.Test)

Example 2 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project hibernate-orm by hibernate.

the class SQLExceptionConversionTest method testNotNullConstraint.

@Test
@TestForIssue(jiraKey = "HHH-7357")
public void testNotNullConstraint() {
    final Session session = openSession();
    session.beginTransaction();
    final User user = new User();
    user.setUsername("Lukasz");
    session.save(user);
    session.flush();
    session.doWork(new Work() {

        @Override
        public void execute(Connection connection) throws SQLException {
            final JdbcCoordinator jdbcCoordinator = ((SessionImplementor) session).getJdbcCoordinator();
            final StatementPreparer statementPreparer = jdbcCoordinator.getStatementPreparer();
            final ResultSetReturn resultSetReturn = jdbcCoordinator.getResultSetReturn();
            PreparedStatement ps = null;
            try {
                ps = statementPreparer.prepareStatement("UPDATE T_USER SET user_name = ? WHERE user_id = ?");
                // Attempt to update user name to NULL (NOT NULL constraint defined).
                ps.setNull(1, Types.VARCHAR);
                ps.setLong(2, user.getId());
                resultSetReturn.executeUpdate(ps);
                fail("UPDATE should have failed because of not NULL constraint.");
            } catch (ConstraintViolationException ignore) {
            // expected outcome
            } finally {
                releaseStatement(session, ps);
            }
        }
    });
    session.getTransaction().rollback();
    session.close();
}
Also used : ResultSetReturn(org.hibernate.engine.jdbc.spi.ResultSetReturn) JdbcCoordinator(org.hibernate.engine.jdbc.spi.JdbcCoordinator) SQLException(java.sql.SQLException) Work(org.hibernate.jdbc.Work) Connection(java.sql.Connection) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) PreparedStatement(java.sql.PreparedStatement) StatementPreparer(org.hibernate.engine.jdbc.spi.StatementPreparer) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 3 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project hibernate-orm by hibernate.

the class SQLStateConversionDelegate method convert.

@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
    final String sqlState = JdbcExceptionHelper.extractSqlState(sqlException);
    final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException);
    if (sqlState != null) {
        String sqlStateClassCode = JdbcExceptionHelper.determineSqlStateClassCode(sqlState);
        if (sqlStateClassCode != null) {
            if (SQL_GRAMMAR_CATEGORIES.contains(sqlStateClassCode)) {
                return new SQLGrammarException(message, sqlException, sql);
            } else if (INTEGRITY_VIOLATION_CATEGORIES.contains(sqlStateClassCode)) {
                final String constraintName = getConversionContext().getViolatedConstraintNameExtracter().extractConstraintName(sqlException);
                return new ConstraintViolationException(message, sqlException, sql, constraintName);
            } else if (CONNECTION_CATEGORIES.contains(sqlStateClassCode)) {
                return new JDBCConnectionException(message, sqlException, sql);
            } else if (DATA_CATEGORIES.contains(sqlStateClassCode)) {
                return new DataException(message, sqlException, sql);
            }
        }
        if ("40001".equals(sqlState)) {
            return new LockAcquisitionException(message, sqlException, sql);
        }
        if ("40XL1".equals(sqlState) || "40XL2".equals(sqlState)) {
            // Derby "A lock could not be obtained within the time requested."
            return new PessimisticLockException(message, sqlException, sql);
        }
        // MySQL Query execution was interrupted
        if ("70100".equals(sqlState) || // Oracle user requested cancel of current operation
        ("72000".equals(sqlState) && errorCode == 1013)) {
            throw new QueryTimeoutException(message, sqlException, sql);
        }
    }
    return null;
}
Also used : DataException(org.hibernate.exception.DataException) QueryTimeoutException(org.hibernate.QueryTimeoutException) JDBCConnectionException(org.hibernate.exception.JDBCConnectionException) SQLGrammarException(org.hibernate.exception.SQLGrammarException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) PessimisticLockException(org.hibernate.PessimisticLockException)

Example 4 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project midpoint by Evolveum.

the class ObjectUpdater method modifyObjectAttempt.

public <T extends ObjectType> void modifyObjectAttempt(Class<T> type, String oid, Collection<? extends ItemDelta> modifications, RepoModifyOptions modifyOptions, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, SerializationRelatedException {
    // clone - because some certification and lookup table related methods manipulate this collection and even their constituent deltas
    // TODO clone elements only if necessary
    modifications = CloneUtil.cloneCollectionMembers(modifications);
    //modifications = new ArrayList<>(modifications);
    LOGGER.debug("Modifying object '{}' with oid '{}'.", new Object[] { type.getSimpleName(), oid });
    LOGGER_PERFORMANCE.debug("> modify object {}, oid={}, modifications={}", type.getSimpleName(), oid, modifications);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Modifications:\n{}", DebugUtil.debugDump(modifications));
    }
    Session session = null;
    OrgClosureManager.Context closureContext = null;
    try {
        session = baseHelper.beginTransaction();
        closureContext = closureManager.onBeginTransactionModify(session, type, oid, modifications);
        Collection<? extends ItemDelta> lookupTableModifications = lookupTableHelper.filterLookupTableModifications(type, modifications);
        Collection<? extends ItemDelta> campaignCaseModifications = caseHelper.filterCampaignCaseModifications(type, modifications);
        if (!modifications.isEmpty() || RepoModifyOptions.isExecuteIfNoChanges(modifyOptions)) {
            // JpegPhoto (RFocusPhoto) is a special kind of entity. First of all, it is lazily loaded, because photos are really big.
            // Each RFocusPhoto naturally belongs to one RFocus, so it would be appropriate to set orphanRemoval=true for focus-photo
            // association. However, this leads to a strange problem when merging in-memory RFocus object with the database state:
            // If in-memory RFocus object has no photo associated (because of lazy loading), then the associated RFocusPhoto is deleted.
            //
            // To prevent this behavior, we've set orphanRemoval to false. Fortunately, the remove operation on RFocus
            // seems to be still cascaded to RFocusPhoto. What we have to implement ourselves, however, is removal of RFocusPhoto
            // _without_ removing of RFocus. In order to know whether the photo has to be removed, we have to retrieve
            // its value, apply the delta (e.g. if the delta is a DELETE VALUE X, we have to know whether X matches current
            // value of the photo), and if the resulting value is empty, we have to manually delete the RFocusPhoto instance.
            //
            // So the first step is to retrieve the current value of photo - we obviously do this only if the modifications
            // deal with the jpegPhoto property.
            Collection<SelectorOptions<GetOperationOptions>> options;
            boolean containsFocusPhotoModification = FocusType.class.isAssignableFrom(type) && containsPhotoModification(modifications);
            if (containsFocusPhotoModification) {
                options = Collections.singletonList(SelectorOptions.create(FocusType.F_JPEG_PHOTO, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)));
            } else {
                options = null;
            }
            // get object
            PrismObject<T> prismObject = objectRetriever.getObjectInternal(session, type, oid, options, true, result);
            // apply diff
            LOGGER.trace("OBJECT before:\n{}", prismObject.debugDumpLazily());
            PrismObject<T> originalObject = null;
            if (closureManager.isEnabled()) {
                originalObject = prismObject.clone();
            }
            ItemDelta.applyTo(modifications, prismObject);
            LOGGER.trace("OBJECT after:\n{}", prismObject.debugDumpLazily());
            // Continuing the photo treatment: should we remove the (now obsolete) focus photo?
            // We have to test prismObject at this place, because updateFullObject (below) removes photo property from the prismObject.
            boolean shouldPhotoBeRemoved = containsFocusPhotoModification && ((FocusType) prismObject.asObjectable()).getJpegPhoto() == null;
            // merge and update object
            LOGGER.trace("Translating JAXB to data type.");
            ObjectTypeUtil.normalizeAllRelations(prismObject);
            RObject rObject = createDataObjectFromJAXB(prismObject, PrismIdentifierGenerator.Operation.MODIFY);
            rObject.setVersion(rObject.getVersion() + 1);
            updateFullObject(rObject, prismObject);
            LOGGER.trace("Starting merge.");
            session.merge(rObject);
            if (closureManager.isEnabled()) {
                closureManager.updateOrgClosure(originalObject, modifications, session, oid, type, OrgClosureManager.Operation.MODIFY, closureContext);
            }
            // we have to remove the photo manually.
            if (shouldPhotoBeRemoved) {
                Query query = session.createQuery("delete RFocusPhoto where ownerOid = :oid");
                query.setParameter("oid", prismObject.getOid());
                query.executeUpdate();
                LOGGER.trace("Focus photo for {} was deleted", prismObject.getOid());
            }
        }
        if (LookupTableType.class.isAssignableFrom(type)) {
            lookupTableHelper.updateLookupTableData(session, oid, lookupTableModifications);
        }
        if (AccessCertificationCampaignType.class.isAssignableFrom(type)) {
            caseHelper.updateCampaignCases(session, oid, campaignCaseModifications, modifyOptions);
        }
        LOGGER.trace("Before commit...");
        session.getTransaction().commit();
        LOGGER.trace("Committed!");
    } catch (ObjectNotFoundException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (ConstraintViolationException ex) {
        handleConstraintViolationException(session, ex, result);
        baseHelper.rollbackTransaction(session, ex, result, true);
        LOGGER.debug("Constraint violation occurred (will be rethrown as ObjectAlreadyExistsException).", ex);
        //todo improve (we support only 5 DB, so we should probably do some hacking in here)
        throw new ObjectAlreadyExistsException(ex);
    } catch (SchemaException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (DtoTranslationException | RuntimeException ex) {
        baseHelper.handleGeneralException(ex, session, result);
    } finally {
        cleanupClosureAndSessionAndResult(closureContext, session, result);
        LOGGER.trace("Session cleaned up.");
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) SQLQuery(org.hibernate.SQLQuery) Query(org.hibernate.Query) DtoTranslationException(com.evolveum.midpoint.repo.sql.util.DtoTranslationException) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) FocusType(com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) Session(org.hibernate.Session)

Example 5 with ConstraintViolationException

use of org.hibernate.exception.ConstraintViolationException in project ART-TIME by Artezio.

the class MessagesUtil method addError.

public static void addError(Throwable throwable) {
    String key = null;
    ResourceBundle resourceBundle = ResourceBundle.getBundle(getMessageBundle(), getCurrentLocale());
    while (throwable != null) {
        key = (throwable instanceof ConstraintViolationException) ? getConstraintViolationExceptionKey((ConstraintViolationException) throwable) : throwable.getClass().getName();
        if (resourceBundle.containsKey(key))
            break;
        throwable = throwable.getCause();
    }
    addError(null, key);
}
Also used : ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) ResourceBundle(java.util.ResourceBundle)

Aggregations

ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)38 Test (org.junit.Test)16 PersistenceException (javax.persistence.PersistenceException)12 Session (org.hibernate.Session)11 SQLException (java.sql.SQLException)7 RObject (com.evolveum.midpoint.repo.sql.data.common.RObject)4 ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)4 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)4 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)4 HttpHeaders (org.springframework.http.HttpHeaders)4 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)4 User (ca.corefacility.bioinformatics.irida.model.user.User)3 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)3 Connection (java.sql.Connection)3 AbstractManyToManyAssociationClassTest (org.hibernate.test.manytomanyassociationclass.AbstractManyToManyAssociationClassTest)3 ResultModels (eu.bcvsolutions.idm.core.api.dto.ResultModels)2 DefaultErrorModel (eu.bcvsolutions.idm.core.api.exception.DefaultErrorModel)2 ErrorModel (eu.bcvsolutions.idm.core.api.exception.ErrorModel)2 ErrorData (io.crnk.core.engine.document.ErrorData)2 PreparedStatement (java.sql.PreparedStatement)2