Search in sources :

Example 46 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 47 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 48 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 49 with SessionFactoryImplementor

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

the class TypeFactorySerializationTest method testUnregisterSerializeRegisterDiffSessionFactory.

@Test
public void testUnregisterSerializeRegisterDiffSessionFactory() throws Exception {
    Configuration cfg = new Configuration().setProperty(AvailableSettings.SESSION_FACTORY_NAME, NAME).setProperty(AvailableSettings.SESSION_FACTORY_NAME_IS_JNDI, // default is true
    "false");
    SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory();
    assertSame(factory, SessionFactoryRegistry.INSTANCE.getNamedSessionFactory(NAME));
    // Remove the session factory from the registry
    SessionFactoryRegistry.INSTANCE.removeSessionFactory(factory.getUuid(), NAME, false, null);
    assertNull(SessionFactoryRegistry.INSTANCE.findSessionFactory(factory.getUuid(), NAME));
    TypeFactory typeFactory = factory.getTypeResolver().getTypeFactory();
    byte[] typeFactoryBytes = SerializationHelper.serialize(typeFactory);
    typeFactory = (TypeFactory) SerializationHelper.deserialize(typeFactoryBytes);
    try {
        typeFactory.resolveSessionFactory();
        fail("should have failed with HibernateException because session factory is not registered.");
    } catch (HibernateException ex) {
    // expected because the session factory is not registered.
    }
    // Now create a new session factory with the same name; it will have a different UUID.
    SessionFactoryImplementor factoryWithSameName = (SessionFactoryImplementor) cfg.buildSessionFactory();
    assertSame(factoryWithSameName, SessionFactoryRegistry.INSTANCE.getNamedSessionFactory(NAME));
    assertFalse(factory.getUuid().equals(factoryWithSameName.getUuid()));
    // Session factory resolved from typeFactory should be the new session factory
    // (because it is resolved from SessionFactoryRegistry.INSTANCE)
    assertSame(factoryWithSameName, typeFactory.resolveSessionFactory());
    factory.close();
    factoryWithSameName.close();
}
Also used : Configuration(org.hibernate.cfg.Configuration) HibernateException(org.hibernate.HibernateException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) TypeFactory(org.hibernate.type.TypeFactory) Test(org.junit.Test)

Example 50 with SessionFactoryImplementor

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

the class TypeFactorySerializationTest method testUnregisterSerializeRegisterDiffSessionFactoryNoName.

@Test
public void testUnregisterSerializeRegisterDiffSessionFactoryNoName() throws Exception {
    Configuration cfg = new Configuration();
    SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory();
    assertSame(factory, SessionFactoryRegistry.INSTANCE.getSessionFactory(factory.getUuid()));
    // Remove the session factory from the registry
    SessionFactoryRegistry.INSTANCE.removeSessionFactory(factory.getUuid(), null, false, null);
    assertNull(SessionFactoryRegistry.INSTANCE.getSessionFactory(factory.getUuid()));
    TypeFactory typeFactory = factory.getTypeResolver().getTypeFactory();
    byte[] typeFactoryBytes = SerializationHelper.serialize(typeFactory);
    typeFactory = (TypeFactory) SerializationHelper.deserialize(typeFactoryBytes);
    try {
        typeFactory.resolveSessionFactory();
        fail("should have failed with HibernateException because session factory is not registered.");
    } catch (HibernateException ex) {
    // expected because the session factory is not registered.
    }
    // Now create a new session factory with the same name; it will have a different UUID.
    SessionFactoryImplementor factoryWithDiffUuid = (SessionFactoryImplementor) cfg.buildSessionFactory();
    assertSame(factoryWithDiffUuid, SessionFactoryRegistry.INSTANCE.getSessionFactory(factoryWithDiffUuid.getUuid()));
    assertFalse(factory.getUuid().equals(factoryWithDiffUuid.getUuid()));
    // It should not be possible to resolve the session factory with no name configured.
    try {
        typeFactory.resolveSessionFactory();
        fail("should have failed with HibernateException because session factories were not registered with the same non-null name.");
    } catch (HibernateException ex) {
    // expected
    }
    factory.close();
    factoryWithDiffUuid.close();
}
Also used : Configuration(org.hibernate.cfg.Configuration) HibernateException(org.hibernate.HibernateException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) TypeFactory(org.hibernate.type.TypeFactory) Test(org.junit.Test)

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