Search in sources :

Example 1 with IdentifierGenerator

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

the class NewGeneratorMappingsTest method testCompleteSequenceEntity.

@Test
public void testCompleteSequenceEntity() {
    final EntityPersister persister = sessionFactory().getEntityPersister(CompleteSequenceEntity.class.getName());
    IdentifierGenerator generator = persister.getIdentifierGenerator();
    assertTrue(SequenceStyleGenerator.class.isInstance(generator));
    SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator;
    assertEquals(1000, seqGenerator.getDatabaseStructure().getInitialValue());
    assertEquals(52, seqGenerator.getDatabaseStructure().getIncrementSize());
    assertFalse(NoopOptimizer.class.isInstance(seqGenerator.getOptimizer()));
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) NoopOptimizer(org.hibernate.id.enhanced.NoopOptimizer) SequenceStyleGenerator(org.hibernate.id.enhanced.SequenceStyleGenerator) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) Test(org.junit.Test)

Example 2 with IdentifierGenerator

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

the class HibernateSequenceTest method testHibernateSequenceSchema.

@Test
public void testHibernateSequenceSchema() {
    EntityPersister persister = sessionFactory().getEntityPersister(HibernateSequenceEntity.class.getName());
    IdentifierGenerator generator = persister.getIdentifierGenerator();
    Assert.assertTrue(SequenceStyleGenerator.class.isInstance(generator));
    SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator;
    Assert.assertEquals(Table.qualify(null, SCHEMA_NAME, SequenceStyleGenerator.DEF_SEQUENCE_NAME), seqGenerator.getDatabaseStructure().getName());
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) HibernateSequenceEntity(org.hibernate.test.annotations.id.sequences.entities.HibernateSequenceEntity) SequenceStyleGenerator(org.hibernate.id.enhanced.SequenceStyleGenerator) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) Test(org.junit.Test)

Example 3 with IdentifierGenerator

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

the class HqlSqlWalker method postProcessInsert.

@Override
protected void postProcessInsert(AST insert) throws SemanticException, QueryException {
    InsertStatement insertStatement = (InsertStatement) insert;
    insertStatement.validate();
    SelectClause selectClause = insertStatement.getSelectClause();
    Queryable persister = insertStatement.getIntoClause().getQueryable();
    if (!insertStatement.getIntoClause().isExplicitIdInsertion()) {
        // the insert did not explicitly reference the id.  See if
        // 1) that is allowed
        // 2) whether we need to alter the SQL tree to account for id
        final IdentifierGenerator generator = persister.getIdentifierGenerator();
        if (!BulkInsertionCapableIdentifierGenerator.class.isInstance(generator)) {
            throw new QueryException("Invalid identifier generator encountered for implicit id handling as part of bulk insertions");
        }
        final BulkInsertionCapableIdentifierGenerator capableGenerator = BulkInsertionCapableIdentifierGenerator.class.cast(generator);
        if (!capableGenerator.supportsBulkInsertionIdentifierGeneration()) {
            throw new QueryException("Identifier generator reported it does not support implicit id handling as part of bulk insertions");
        }
        final String fragment = capableGenerator.determineBulkInsertionIdentifierGenerationSelectFragment(sessionFactoryHelper.getFactory().getDialect());
        if (fragment != null) {
            // we got a fragment from the generator, so alter the sql tree...
            // 
            // first, wrap the fragment as a node
            AST fragmentNode = getASTFactory().create(HqlSqlTokenTypes.SQL_TOKEN, fragment);
            // next, rearrange the SQL tree to add the fragment node as the first select expression
            AST originalFirstSelectExprNode = selectClause.getFirstChild();
            selectClause.setFirstChild(fragmentNode);
            fragmentNode.setNextSibling(originalFirstSelectExprNode);
            // finally, prepend the id column name(s) to the insert-spec
            insertStatement.getIntoClause().prependIdColumnSpec();
        }
    }
    if (sessionFactoryHelper.getFactory().getDialect().supportsParametersInInsertSelect()) {
        AST child = selectClause.getFirstChild();
        int i = 0;
        while (child != null) {
            if (child instanceof ParameterNode) {
                // infer the parameter type from the type listed in the INSERT INTO clause
                ((ParameterNode) child).setExpectedType(insertStatement.getIntoClause().getInsertionTypes()[selectClause.getParameterPositions().get(i)]);
                i++;
            }
            child = child.getNextSibling();
        }
    }
    final boolean includeVersionProperty = persister.isVersioned() && !insertStatement.getIntoClause().isExplicitVersionInsertion() && persister.isVersionPropertyInsertable();
    if (includeVersionProperty) {
        // We need to seed the version value as part of this bulk insert
        VersionType versionType = persister.getVersionType();
        AST versionValueNode = null;
        if (sessionFactoryHelper.getFactory().getDialect().supportsParametersInInsertSelect()) {
            int[] sqlTypes = versionType.sqlTypes(sessionFactoryHelper.getFactory());
            if (sqlTypes == null || sqlTypes.length == 0) {
                throw new IllegalStateException(versionType.getClass() + ".sqlTypes() returns null or empty array");
            }
            if (sqlTypes.length > 1) {
                throw new IllegalStateException(versionType.getClass() + ".sqlTypes() returns > 1 element; only single-valued versions are allowed.");
            }
            versionValueNode = getASTFactory().create(HqlSqlTokenTypes.PARAM, "?");
            ParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification(versionType);
            ((ParameterNode) versionValueNode).setHqlParameterSpecification(paramSpec);
            parameterSpecs.add(0, paramSpec);
            if (sessionFactoryHelper.getFactory().getDialect().requiresCastingOfParametersInSelectClause()) {
                // we need to wrtap the param in a cast()
                MethodNode versionMethodNode = (MethodNode) getASTFactory().create(HqlSqlTokenTypes.METHOD_CALL, "(");
                AST methodIdentNode = getASTFactory().create(HqlSqlTokenTypes.IDENT, "cast");
                versionMethodNode.addChild(methodIdentNode);
                versionMethodNode.initializeMethodNode(methodIdentNode, true);
                AST castExprListNode = getASTFactory().create(HqlSqlTokenTypes.EXPR_LIST, "exprList");
                methodIdentNode.setNextSibling(castExprListNode);
                castExprListNode.addChild(versionValueNode);
                versionValueNode.setNextSibling(getASTFactory().create(HqlSqlTokenTypes.IDENT, sessionFactoryHelper.getFactory().getDialect().getTypeName(sqlTypes[0])));
                processFunction(versionMethodNode, true);
                versionValueNode = versionMethodNode;
            }
        } else {
            if (isIntegral(versionType)) {
                try {
                    Object seedValue = versionType.seed(null);
                    versionValueNode = getASTFactory().create(HqlSqlTokenTypes.SQL_TOKEN, seedValue.toString());
                } catch (Throwable t) {
                    throw new QueryException("could not determine seed value for version on bulk insert [" + versionType + "]");
                }
            } else if (isDatabaseGeneratedTimestamp(versionType)) {
                String functionName = sessionFactoryHelper.getFactory().getDialect().getCurrentTimestampSQLFunctionName();
                versionValueNode = getASTFactory().create(HqlSqlTokenTypes.SQL_TOKEN, functionName);
            } else {
                throw new QueryException("cannot handle version type [" + versionType + "] on bulk inserts with dialects not supporting parameterSpecs in insert-select statements");
            }
        }
        AST currentFirstSelectExprNode = selectClause.getFirstChild();
        selectClause.setFirstChild(versionValueNode);
        versionValueNode.setNextSibling(currentFirstSelectExprNode);
        insertStatement.getIntoClause().prependVersionColumnSpec();
    }
    if (insertStatement.getIntoClause().isDiscriminated()) {
        String sqlValue = insertStatement.getIntoClause().getQueryable().getDiscriminatorSQLValue();
        AST discrimValue = getASTFactory().create(HqlSqlTokenTypes.SQL_TOKEN, sqlValue);
        insertStatement.getSelectClause().addChild(discrimValue);
    }
}
Also used : SelectClause(org.hibernate.hql.internal.ast.tree.SelectClause) AST(antlr.collections.AST) CollectionFilterKeyParameterSpecification(org.hibernate.param.CollectionFilterKeyParameterSpecification) ParameterSpecification(org.hibernate.param.ParameterSpecification) PositionalParameterSpecification(org.hibernate.param.PositionalParameterSpecification) VersionTypeSeedParameterSpecification(org.hibernate.param.VersionTypeSeedParameterSpecification) NamedParameterSpecification(org.hibernate.param.NamedParameterSpecification) VersionTypeSeedParameterSpecification(org.hibernate.param.VersionTypeSeedParameterSpecification) Queryable(org.hibernate.persister.entity.Queryable) InsertStatement(org.hibernate.hql.internal.ast.tree.InsertStatement) UserVersionType(org.hibernate.usertype.UserVersionType) VersionType(org.hibernate.type.VersionType) BulkInsertionCapableIdentifierGenerator(org.hibernate.id.BulkInsertionCapableIdentifierGenerator) QueryException(org.hibernate.QueryException) ParameterNode(org.hibernate.hql.internal.ast.tree.ParameterNode) MethodNode(org.hibernate.hql.internal.ast.tree.MethodNode) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) BulkInsertionCapableIdentifierGenerator(org.hibernate.id.BulkInsertionCapableIdentifierGenerator)

Example 4 with IdentifierGenerator

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

the class GeneratedValueTests method baseline.

@Test
public void baseline() {
    final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
    final Metadata bootModel = new MetadataSources(ssr).addAnnotatedClass(ExplicitGeneratorEntity.class).buildMetadata();
    final PersistentClass entityMapping = bootModel.getEntityBinding(ExplicitGeneratorEntity.class.getName());
    final IdentifierGenerator generator = entityMapping.getIdentifier().createIdentifierGenerator(bootModel.getIdentifierGeneratorFactory(), ssr.getService(JdbcEnvironment.class).getDialect(), null, null, (RootClass) entityMapping);
    final SequenceStyleGenerator sequenceStyleGenerator = assertTyping(SequenceStyleGenerator.class, generator);
    assertThat(sequenceStyleGenerator.getDatabaseStructure().getName(), is("my_real_db_sequence"));
    // all the JPA defaults since they were not defined
    assertThat(sequenceStyleGenerator.getDatabaseStructure().getInitialValue(), is(100));
    assertThat(sequenceStyleGenerator.getDatabaseStructure().getIncrementSize(), is(500));
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) SequenceStyleGenerator(org.hibernate.id.enhanced.SequenceStyleGenerator) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) PersistentClass(org.hibernate.mapping.PersistentClass) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) Test(org.junit.Test)

Example 5 with IdentifierGenerator

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

the class GeneratedValueTests method testExplicitIncrementGenerator.

@Test
public void testExplicitIncrementGenerator() {
    final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
    final Metadata bootModel = new MetadataSources(ssr).addAnnotatedClass(ExplicitIncrementGeneratorEntity.class).buildMetadata();
    final PersistentClass entityMapping = bootModel.getEntityBinding(ExplicitIncrementGeneratorEntity.class.getName());
    final IdentifierGenerator generator = entityMapping.getIdentifier().createIdentifierGenerator(bootModel.getIdentifierGeneratorFactory(), ssr.getService(JdbcEnvironment.class).getDialect(), null, null, (RootClass) entityMapping);
    assertTyping(IncrementGenerator.class, generator);
}
Also used : StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Metadata(org.hibernate.boot.Metadata) MetadataSources(org.hibernate.boot.MetadataSources) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) PersistentClass(org.hibernate.mapping.PersistentClass) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) Test(org.junit.Test)

Aggregations

IdentifierGenerator (org.hibernate.id.IdentifierGenerator)22 Test (org.junit.Test)18 Metadata (org.hibernate.boot.Metadata)11 MetadataSources (org.hibernate.boot.MetadataSources)11 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)11 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)11 PersistentClass (org.hibernate.mapping.PersistentClass)11 SequenceStyleGenerator (org.hibernate.id.enhanced.SequenceStyleGenerator)10 EntityPersister (org.hibernate.persister.entity.EntityPersister)8 TableGenerator (org.hibernate.id.enhanced.TableGenerator)4 BulkInsertionCapableIdentifierGenerator (org.hibernate.id.BulkInsertionCapableIdentifierGenerator)2 NoopOptimizer (org.hibernate.id.enhanced.NoopOptimizer)2 AST (antlr.collections.AST)1 Iterator (java.util.Iterator)1 MappingException (org.hibernate.MappingException)1 QueryException (org.hibernate.QueryException)1 Session (org.hibernate.Session)1 SessionFactory (org.hibernate.SessionFactory)1 MetadataImpl (org.hibernate.boot.internal.MetadataImpl)1 Sequence (org.hibernate.boot.model.relational.Sequence)1