Search in sources :

Example 1 with IdentifierGenerationException

use of org.hibernate.id.IdentifierGenerationException in project hibernate-orm by hibernate.

the class AbstractSaveEventListener method saveWithGeneratedId.

/**
	 * Prepares the save call using a newly generated id.
	 *
	 * @param entity The entity to be saved
	 * @param entityName The entity-name for the entity to be saved
	 * @param anything Generally cascade-specific information.
	 * @param source The session which is the source of this save event.
	 * @param requiresImmediateIdAccess does the event context require
	 * access to the identifier immediately afterQuery execution of this method (if
	 * not, post-insert style id generators may be postponed if we are outside
	 * a transaction).
	 *
	 * @return The id used to save the entity; may be null depending on the
	 *         type of id generator used and the requiresImmediateIdAccess value
	 */
protected Serializable saveWithGeneratedId(Object entity, String entityName, Object anything, EventSource source, boolean requiresImmediateIdAccess) {
    if (entity instanceof SelfDirtinessTracker) {
        ((SelfDirtinessTracker) entity).$$_hibernate_clearDirtyAttributes();
    }
    EntityPersister persister = source.getEntityPersister(entityName, entity);
    Serializable generatedId = persister.getIdentifierGenerator().generate(source, entity);
    if (generatedId == null) {
        throw new IdentifierGenerationException("null id generated for:" + entity.getClass());
    } else if (generatedId == IdentifierGeneratorHelper.SHORT_CIRCUIT_INDICATOR) {
        return source.getIdentifier(entity);
    } else if (generatedId == IdentifierGeneratorHelper.POST_INSERT_INDICATOR) {
        return performSave(entity, null, persister, true, anything, source, requiresImmediateIdAccess);
    } else {
        // TODO: define toString()s for generators
        if (LOG.isDebugEnabled()) {
            LOG.debugf("Generated identifier: %s, using strategy: %s", persister.getIdentifierType().toLoggableString(generatedId, source.getFactory()), persister.getIdentifierGenerator().getClass().getName());
        }
        return performSave(entity, generatedId, persister, false, anything, source, true);
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) IdentifierGenerationException(org.hibernate.id.IdentifierGenerationException) SelfDirtinessTracker(org.hibernate.engine.spi.SelfDirtinessTracker)

Example 2 with IdentifierGenerationException

use of org.hibernate.id.IdentifierGenerationException in project hibernate-orm by hibernate.

the class OptionalOneToOneMappedByTest method testBidirForeignIdGenerator.

// @OneToOne(mappedBy="address") with foreign generator
@Test
public void testBidirForeignIdGenerator() {
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    OwnerAddress address = new OwnerAddress();
    address.setOwner(null);
    try {
        s.persist(address);
        s.flush();
        fail("should have failed with IdentifierGenerationException");
    } catch (PersistenceException ex) {
        assertTyping(IdentifierGenerationException.class, ex.getCause());
    // expected
    } finally {
        tx.rollback();
    }
    s.close();
}
Also used : Transaction(org.hibernate.Transaction) PersistenceException(javax.persistence.PersistenceException) IdentifierGenerationException(org.hibernate.id.IdentifierGenerationException) Session(org.hibernate.Session) Test(org.junit.Test)

Example 3 with IdentifierGenerationException

use of org.hibernate.id.IdentifierGenerationException in project hibernate-orm by hibernate.

the class OptionalOneToOnePKJCTest method testNotFoundBidirForeignIdGenerator.

@Test
@TestForIssue(jiraKey = "HHH-4982")
public void testNotFoundBidirForeignIdGenerator() {
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    Person person = new Person();
    person.setPersonAddress(null);
    person.setId(1);
    try {
        // Hibernate resets the ID to null beforeQuery executing the foreign generator
        s.persist(person);
        s.flush();
        fail("should have thrown IdentifierGenerationException.");
    } catch (PersistenceException ex) {
        assertTyping(IdentifierGenerationException.class, ex.getCause());
    // expected
    } finally {
        tx.rollback();
        s.close();
    }
}
Also used : Transaction(org.hibernate.Transaction) PersistenceException(javax.persistence.PersistenceException) IdentifierGenerationException(org.hibernate.id.IdentifierGenerationException) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 4 with IdentifierGenerationException

use of org.hibernate.id.IdentifierGenerationException in project hibernate-orm by hibernate.

the class OptionalOneToOnePKJCTest method testNullBidirForeignIdGenerator.

@Test
@TestForIssue(jiraKey = "HHH-4982")
public void testNullBidirForeignIdGenerator() {
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    Person person = new Person();
    person.setPersonAddress(null);
    try {
        s.persist(person);
        s.flush();
        fail("should have thrown IdentifierGenerationException.");
    } catch (PersistenceException ex) {
        assertTyping(IdentifierGenerationException.class, ex.getCause());
    // expected
    } finally {
        tx.rollback();
        s.close();
    }
}
Also used : Transaction(org.hibernate.Transaction) PersistenceException(javax.persistence.PersistenceException) IdentifierGenerationException(org.hibernate.id.IdentifierGenerationException) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 5 with IdentifierGenerationException

use of org.hibernate.id.IdentifierGenerationException in project hibernate-orm by hibernate.

the class TableStructure method buildCallback.

@Override
public AccessCallback buildCallback(final SharedSessionContractImplementor session) {
    final SqlStatementLogger statementLogger = session.getFactory().getServiceRegistry().getService(JdbcServices.class).getSqlStatementLogger();
    if (selectQuery == null || updateQuery == null) {
        throw new AssertionFailure("SequenceStyleGenerator's TableStructure was not properly initialized");
    }
    final SessionEventListenerManager statsCollector = session.getEventListenerManager();
    return new AccessCallback() {

        @Override
        public IntegralDataTypeHolder getNextValue() {
            return session.getTransactionCoordinator().createIsolationDelegate().delegateWork(new AbstractReturningWork<IntegralDataTypeHolder>() {

                @Override
                public IntegralDataTypeHolder execute(Connection connection) throws SQLException {
                    final IntegralDataTypeHolder value = makeValue();
                    int rows;
                    do {
                        try (PreparedStatement selectStatement = prepareStatement(connection, selectQuery, statementLogger, statsCollector)) {
                            final ResultSet selectRS = executeQuery(selectStatement, statsCollector);
                            if (!selectRS.next()) {
                                final String err = "could not read a hi value - you need to populate the table: " + tableNameText;
                                LOG.error(err);
                                throw new IdentifierGenerationException(err);
                            }
                            value.initialize(selectRS, 1);
                            selectRS.close();
                        } catch (SQLException sqle) {
                            LOG.error("could not read a hi value", sqle);
                            throw sqle;
                        }
                        try (PreparedStatement updatePS = prepareStatement(connection, updateQuery, statementLogger, statsCollector)) {
                            final int increment = applyIncrementSizeToSourceValues ? incrementSize : 1;
                            final IntegralDataTypeHolder updateValue = value.copy().add(increment);
                            updateValue.bind(updatePS, 1);
                            value.bind(updatePS, 2);
                            rows = executeUpdate(updatePS, statsCollector);
                        } catch (SQLException e) {
                            LOG.unableToUpdateQueryHiValue(tableNameText, e);
                            throw e;
                        }
                    } while (rows == 0);
                    accessCounter++;
                    return value;
                }
            }, true);
        }

        @Override
        public String getTenantIdentifier() {
            return session.getTenantIdentifier();
        }
    };
}
Also used : AssertionFailure(org.hibernate.AssertionFailure) SQLException(java.sql.SQLException) Connection(java.sql.Connection) IdentifierGenerationException(org.hibernate.id.IdentifierGenerationException) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet) SqlStatementLogger(org.hibernate.engine.jdbc.spi.SqlStatementLogger) SessionEventListenerManager(org.hibernate.engine.spi.SessionEventListenerManager) IntegralDataTypeHolder(org.hibernate.id.IntegralDataTypeHolder)

Aggregations

IdentifierGenerationException (org.hibernate.id.IdentifierGenerationException)5 PersistenceException (javax.persistence.PersistenceException)3 Session (org.hibernate.Session)3 Transaction (org.hibernate.Transaction)3 Test (org.junit.Test)3 TestForIssue (org.hibernate.testing.TestForIssue)2 Serializable (java.io.Serializable)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 AssertionFailure (org.hibernate.AssertionFailure)1 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)1 SqlStatementLogger (org.hibernate.engine.jdbc.spi.SqlStatementLogger)1 SelfDirtinessTracker (org.hibernate.engine.spi.SelfDirtinessTracker)1 SessionEventListenerManager (org.hibernate.engine.spi.SessionEventListenerManager)1 IntegralDataTypeHolder (org.hibernate.id.IntegralDataTypeHolder)1 EntityPersister (org.hibernate.persister.entity.EntityPersister)1