Search in sources :

Example 26 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class InLogicOperatorNode method initialize.

@Override
public void initialize() throws SemanticException {
    final Node lhs = getLeftHandOperand();
    if (lhs == null) {
        throw new SemanticException("left-hand operand of in operator was null");
    }
    final Node inList = getInList();
    if (inList == null) {
        throw new SemanticException("right-hand operand of in operator was null");
    }
    // one-or-more params.
    if (SqlNode.class.isAssignableFrom(lhs.getClass())) {
        Type lhsType = ((SqlNode) lhs).getDataType();
        AST inListChild = inList.getFirstChild();
        while (inListChild != null) {
            if (ExpectedTypeAwareNode.class.isAssignableFrom(inListChild.getClass())) {
                ((ExpectedTypeAwareNode) inListChild).setExpectedType(lhsType);
            }
            // fix for HHH-9605
            if (CollectionFunction.class.isInstance(inListChild) && ExpectedTypeAwareNode.class.isInstance(lhs)) {
                final Type rhsType = ((CollectionFunction) inListChild).getDataType();
                ((ExpectedTypeAwareNode) lhs).setExpectedType(rhsType);
            }
            inListChild = inListChild.getNextSibling();
        }
    }
    final SessionFactoryImplementor sessionFactory = getSessionFactoryHelper().getFactory();
    if (sessionFactory.getDialect().supportsRowValueConstructorSyntaxInInList()) {
        return;
    }
    final Type lhsType = extractDataType(lhs);
    if (lhsType == null) {
        return;
    }
    final int lhsColumnSpan = lhsType.getColumnSpan(sessionFactory);
    final Node rhsNode = (Node) inList.getFirstChild();
    if (!isNodeAcceptable(rhsNode)) {
        return;
    }
    int rhsColumnSpan;
    if (rhsNode == null) {
        // early exit for empty IN list
        return;
    } else if (rhsNode.getType() == HqlTokenTypes.VECTOR_EXPR) {
        rhsColumnSpan = rhsNode.getNumberOfChildren();
    } else {
        final Type rhsType = extractDataType(rhsNode);
        if (rhsType == null) {
            return;
        }
        rhsColumnSpan = rhsType.getColumnSpan(sessionFactory);
    }
    if (lhsColumnSpan > 1 && rhsColumnSpan > 1) {
        mutateRowValueConstructorSyntaxInInListSyntax(lhsColumnSpan, rhsColumnSpan);
    }
}
Also used : Type(org.hibernate.type.Type) AST(antlr.collections.AST) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SemanticException(antlr.SemanticException)

Example 27 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class MapKeyEntityFromElement method buildKeyJoin.

public static MapKeyEntityFromElement buildKeyJoin(FromElement collectionFromElement) {
    final HqlSqlWalker walker = collectionFromElement.getWalker();
    final SessionFactoryHelper sfh = walker.getSessionFactoryHelper();
    final SessionFactoryImplementor sf = sfh.getFactory();
    final QueryableCollection collectionPersister = collectionFromElement.getQueryableCollection();
    final Type indexType = collectionPersister.getIndexType();
    if (indexType == null) {
        throw new IllegalArgumentException("Given collection is not indexed");
    }
    if (!indexType.isEntityType()) {
        throw new IllegalArgumentException("Given collection does not have an entity index");
    }
    final EntityType indexEntityType = (EntityType) indexType;
    final EntityPersister indexEntityPersister = (EntityPersister) indexEntityType.getAssociatedJoinable(sf);
    final String rhsAlias = walker.getAliasGenerator().createName(indexEntityPersister.getEntityName());
    final boolean useThetaJoin = collectionFromElement.getJoinSequence().isThetaStyle();
    MapKeyEntityFromElement join = new MapKeyEntityFromElement(useThetaJoin);
    join.initialize(HqlSqlTokenTypes.JOIN_FRAGMENT, ((Joinable) indexEntityPersister).getTableName());
    join.initialize(collectionFromElement.getWalker());
    join.initializeEntity(collectionFromElement.getFromClause(), indexEntityPersister.getEntityName(), indexEntityPersister, indexEntityType, "<map-key-join-" + collectionFromElement.getClassAlias() + ">", rhsAlias);
    //		String[] joinColumns = determineJoinColuns( collectionPersister, joinTableAlias );
    // todo : assumes columns, no formulas
    String[] joinColumns = collectionPersister.getIndexColumnNames(collectionFromElement.getCollectionTableAlias());
    JoinSequence joinSequence = sfh.createJoinSequence(useThetaJoin, indexEntityType, rhsAlias, //				JoinType.INNER_JOIN,
    collectionFromElement.getJoinSequence().getFirstJoin().getJoinType(), joinColumns);
    join.setJoinSequence(joinSequence);
    join.setOrigin(collectionFromElement, true);
    join.setColumns(joinColumns);
    join.setUseFromFragment(collectionFromElement.useFromFragment());
    join.setUseWhereFragment(collectionFromElement.useWhereFragment());
    walker.addQuerySpaces(indexEntityPersister.getQuerySpaces());
    return join;
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SessionFactoryHelper(org.hibernate.hql.internal.ast.util.SessionFactoryHelper) QueryableCollection(org.hibernate.persister.collection.QueryableCollection) EntityType(org.hibernate.type.EntityType) JoinType(org.hibernate.sql.JoinType) EntityType(org.hibernate.type.EntityType) Type(org.hibernate.type.Type) HqlSqlWalker(org.hibernate.hql.internal.ast.HqlSqlWalker) JoinSequence(org.hibernate.engine.internal.JoinSequence)

Example 28 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class AbstractLazyInitializer method permissiveInitialization.

protected void permissiveInitialization() {
    if (session == null) {
        //we have a detached collection thats set to null, reattach
        if (sessionFactoryUuid == null) {
            throw new LazyInitializationException("could not initialize proxy - no Session");
        }
        try {
            SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory(sessionFactoryUuid);
            SharedSessionContractImplementor session = (SharedSessionContractImplementor) sf.openSession();
            session.getPersistenceContext().setDefaultReadOnly(true);
            session.setFlushMode(FlushMode.MANUAL);
            boolean isJTA = session.getTransactionCoordinator().getTransactionCoordinatorBuilder().isJta();
            if (!isJTA) {
                // Explicitly handle the transactions only if we're not in
                // a JTA environment.  A lazy loading temporary session can
                // be created even if a current session and transaction are
                // open (ex: session.clear() was used).  We must prevent
                // multiple transactions.
                session.beginTransaction();
            }
            try {
                target = session.immediateLoad(entityName, id);
                initialized = true;
                checkTargetState(session);
            } finally {
                // make sure the just opened temp session gets closed!
                try {
                    if (!isJTA) {
                        session.getTransaction().commit();
                    }
                    session.close();
                } catch (Exception e) {
                    log.warn("Unable to close temporary session used to load lazy proxy associated to no session");
                }
            }
        } catch (Exception e) {
            log.error("Initialization failure", e);
            throw new LazyInitializationException(e.getMessage());
        }
    } else if (session.isOpen() && session.isConnected()) {
        target = session.immediateLoad(entityName, id);
        initialized = true;
        checkTargetState(session);
    } else {
        throw new LazyInitializationException("could not initialize proxy - Session was closed or disced");
    }
}
Also used : LazyInitializationException(org.hibernate.LazyInitializationException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) TransientObjectException(org.hibernate.TransientObjectException) LazyInitializationException(org.hibernate.LazyInitializationException) HibernateException(org.hibernate.HibernateException) SessionException(org.hibernate.SessionException)

Example 29 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class CriteriaCompiler method compile.

public QueryImplementor compile(CompilableCriteria criteria) {
    try {
        criteria.validate();
    } catch (IllegalStateException ise) {
        throw new IllegalArgumentException("Error occurred validating the Criteria", ise);
    }
    final Map<ParameterExpression<?>, ExplicitParameterInfo<?>> explicitParameterInfoMap = new HashMap<>();
    final List<ImplicitParameterBinding> implicitParameterBindings = new ArrayList<>();
    RenderingContext renderingContext = new RenderingContext() {

        private int aliasCount;

        private int explicitParameterCount;

        public String generateAlias() {
            return "generatedAlias" + aliasCount++;
        }

        public String generateParameterName() {
            return "param" + explicitParameterCount++;
        }

        @Override
        @SuppressWarnings("unchecked")
        public ExplicitParameterInfo registerExplicitParameter(ParameterExpression<?> criteriaQueryParameter) {
            ExplicitParameterInfo parameterInfo = explicitParameterInfoMap.get(criteriaQueryParameter);
            if (parameterInfo == null) {
                if (StringHelper.isNotEmpty(criteriaQueryParameter.getName())) {
                    parameterInfo = new ExplicitParameterInfo(criteriaQueryParameter.getName(), null, criteriaQueryParameter.getJavaType());
                } else if (criteriaQueryParameter.getPosition() != null) {
                    parameterInfo = new ExplicitParameterInfo(null, criteriaQueryParameter.getPosition(), criteriaQueryParameter.getJavaType());
                } else {
                    parameterInfo = new ExplicitParameterInfo(generateParameterName(), null, criteriaQueryParameter.getJavaType());
                }
                explicitParameterInfoMap.put(criteriaQueryParameter, parameterInfo);
            }
            return parameterInfo;
        }

        public String registerLiteralParameterBinding(final Object literal, final Class javaType) {
            final String parameterName = generateParameterName();
            final ImplicitParameterBinding binding = new ImplicitParameterBinding() {

                public String getParameterName() {
                    return parameterName;
                }

                public Class getJavaType() {
                    return javaType;
                }

                public void bind(TypedQuery typedQuery) {
                    typedQuery.setParameter(parameterName, literal);
                }
            };
            implicitParameterBindings.add(binding);
            return parameterName;
        }

        public String getCastType(Class javaType) {
            SessionFactoryImplementor factory = entityManager.getFactory();
            Type hibernateType = factory.getTypeResolver().heuristicType(javaType.getName());
            if (hibernateType == null) {
                throw new IllegalArgumentException("Could not convert java type [" + javaType.getName() + "] to Hibernate type");
            }
            return hibernateType.getName();
        }
    };
    return criteria.interpret(renderingContext).buildCompiledQuery(entityManager, new InterpretedParameterMetadata() {

        @Override
        public Map<ParameterExpression<?>, ExplicitParameterInfo<?>> explicitParameterInfoMap() {
            return explicitParameterInfoMap;
        }

        @Override
        public List<ImplicitParameterBinding> implicitParameterBindings() {
            return implicitParameterBindings;
        }
    });
}
Also used : HashMap(java.util.HashMap) TypedQuery(javax.persistence.TypedQuery) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) ArrayList(java.util.ArrayList) Type(org.hibernate.type.Type) ParameterExpression(javax.persistence.criteria.ParameterExpression) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap)

Example 30 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class InformixDialectTestCase method testCurrentTimestampFunction.

@Test
@TestForIssue(jiraKey = "HHH-10800")
public void testCurrentTimestampFunction() {
    Map<String, SQLFunction> functions = dialect.getFunctions();
    SQLFunction sqlFunction = functions.get("current_timestamp");
    Type firstArgumentType = null;
    Mapping mapping = null;
    assertEquals(StandardBasicTypes.TIMESTAMP, sqlFunction.getReturnType(firstArgumentType, mapping));
    firstArgumentType = null;
    List arguments = Collections.emptyList();
    SessionFactoryImplementor factory = null;
    assertEquals("current", sqlFunction.render(firstArgumentType, arguments, factory));
}
Also used : Type(org.hibernate.type.Type) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Mapping(org.hibernate.engine.spi.Mapping) List(java.util.List) SQLFunction(org.hibernate.dialect.function.SQLFunction) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Aggregations

SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)129 Test (org.junit.Test)46 Configuration (org.hibernate.cfg.Configuration)27 SQLException (java.sql.SQLException)18 Type (org.hibernate.type.Type)16 EntityPersister (org.hibernate.persister.entity.EntityPersister)13 Connection (java.sql.Connection)12 HibernateException (org.hibernate.HibernateException)12 PreparedStatement (java.sql.PreparedStatement)11 Metadata (org.hibernate.boot.Metadata)11 Statement (java.sql.Statement)10 ArrayList (java.util.ArrayList)10 JdbcConnectionAccess (org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess)10 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)10 Serializable (java.io.Serializable)9 EncapsulatedCompositeIdResultSetProcessorTest (org.hibernate.test.loadplans.process.EncapsulatedCompositeIdResultSetProcessorTest)8 HashMap (java.util.HashMap)7 Integrator (org.hibernate.integrator.spi.Integrator)7 SessionFactoryServiceRegistry (org.hibernate.service.spi.SessionFactoryServiceRegistry)7 Map (java.util.Map)6