Example usage for org.hibernate.engine.spi SessionImplementor getFactory

List of usage examples for org.hibernate.engine.spi SessionImplementor getFactory

Introduction

In this page you can find the example usage for org.hibernate.engine.spi SessionImplementor getFactory.

Prototype

HibernateEntityManagerFactory getFactory();

Source Link

Document

Get access to the Hibernate extended EMF contract.

Usage

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

private HQLQueryPlan getOriginalQueryPlan(SessionImplementor session, Query query) {
    SessionFactoryImplementor sfi = session.getFactory();
    org.hibernate.Query hibernateQuery = query.unwrap(org.hibernate.Query.class);

    Map<String, TypedValue> namedParams = new HashMap<String, TypedValue>(
            hibernateAccess.getNamedParams(hibernateQuery));
    String queryString = hibernateAccess.expandParameterLists(session, hibernateQuery, namedParams);
    return sfi.getQueryPlanCache().getHQLQueryPlan(queryString, false, Collections.EMPTY_MAP);
}

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

@Override
public int getSqlSelectAttributePosition(EntityManager em, Query query, String expression) {
    if (expression.contains(".")) {
        // TODO: implement
        throw new UnsupportedOperationException("Embeddables are not yet supported!");
    }/*from   ww  w .  j  av a  2 s.  co  m*/

    SessionImplementor session = em.unwrap(SessionImplementor.class);
    HQLQueryPlan plan = getOriginalQueryPlan(session, query);
    if (plan.getTranslators().length > 1) {
        throw new IllegalArgumentException("No support for multiple translators yet!");
    }
    QueryTranslator translator = plan.getTranslators()[0];

    try {
        QueryNode queryNode = getField(translator, "sqlAst");
        SelectClause selectClause = queryNode.getSelectClause();
        Type[] queryReturnTypes = selectClause.getQueryReturnTypes();

        boolean found = false;
        // The ordinal is 1 based
        int position = 1;
        for (int i = 0; i < queryReturnTypes.length; i++) {
            Type t = queryReturnTypes[i];
            if (t instanceof ManyToOneType) {
                ManyToOneType manyToOneType = (ManyToOneType) t;
                AbstractEntityPersister persister = (AbstractEntityPersister) session.getFactory()
                        .getEntityPersister(manyToOneType.getAssociatedEntityName());

                int propertyIndex = persister.getPropertyIndex(expression);
                found = true;
                for (int j = 0; j < propertyIndex; j++) {
                    position += persister.getPropertyColumnNames(j).length;
                }
                // Increment to the actual property position
                position++;
            } else {
                position++;
            }
        }

        if (found) {
            return position;
        }

        AST selectItem = selectClause.getFirstChild();

        while (selectItem != null && (selectItem.getType() == SqlTokenTypes.DISTINCT
                || selectItem.getType() == SqlTokenTypes.ALL)) {
            selectItem = selectItem.getNextSibling();
        }

        position = 1;
        for (AST n = selectItem; n != null; n = n.getNextSibling()) {
            if (n instanceof DotNode) {
                DotNode dot = (DotNode) n;
                if (expression.equals(dot.getPropertyPath())) {
                    // Check if the property is an embeddable
                    if (dot.getText().contains(",")) {
                        throw new IllegalStateException("Can't order by the embeddable: " + expression);
                    }
                    found = true;
                    break;
                }
            }
            position++;
        }

        if (found) {
            return position;
        }

        return -1;
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }
}

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

@SuppressWarnings("rawtypes")
private List list(com.blazebit.persistence.spi.ServiceProvider serviceProvider, EntityManager em,
        List<Query> participatingQueries, Query query, String finalSql) {
    SessionImplementor session = em.unwrap(SessionImplementor.class);
    SessionFactoryImplementor sfi = session.getFactory();

    if (session.isClosed()) {
        throw new PersistenceException("Entity manager is closed!");
    }/*from   www  .  j  a v  a2  s .c om*/

    // Create combined query parameters
    List<String> queryStrings = new ArrayList<>(participatingQueries.size());
    Set<String> querySpaces = new HashSet<>();
    QueryParamEntry queryParametersEntry = createQueryParameters(em, participatingQueries, queryStrings,
            querySpaces);
    QueryParameters queryParameters = queryParametersEntry.queryParameters;

    QueryPlanCacheKey cacheKey = createCacheKey(queryStrings);
    CacheEntry<HQLQueryPlan> queryPlanEntry = getQueryPlan(sfi, query, cacheKey);
    HQLQueryPlan queryPlan = queryPlanEntry.getValue();

    if (!queryPlanEntry.isFromCache()) {
        prepareQueryPlan(queryPlan, queryParametersEntry.specifications, finalSql, session, null, false,
                serviceProvider.getService(DbmsDialect.class));
        queryPlan = putQueryPlanIfAbsent(sfi, cacheKey, queryPlan);
    }

    autoFlush(querySpaces, session);
    return hibernateAccess.performList(queryPlan, session, queryParameters);
}

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

@Override
public int executeUpdate(com.blazebit.persistence.spi.ServiceProvider serviceProvider,
        List<Query> participatingQueries, Query baseQuery, Query query, String finalSql) {
    DbmsDialect dbmsDialect = serviceProvider.getService(DbmsDialect.class);
    EntityManager em = serviceProvider.getService(EntityManager.class);
    SessionImplementor session = em.unwrap(SessionImplementor.class);
    SessionFactoryImplementor sfi = session.getFactory();

    if (session.isClosed()) {
        throw new PersistenceException("Entity manager is closed!");
    }//from  w w w. java2s.c  o m

    Integer firstResult = null;
    Integer maxResults = null;

    if (query.getFirstResult() > 0) {
        firstResult = query.getFirstResult();
    }
    if (query.getMaxResults() != Integer.MAX_VALUE) {
        maxResults = query.getMaxResults();
    }

    // Create combined query parameters
    List<String> queryStrings = new ArrayList<>(participatingQueries.size());
    Set<String> querySpaces = new HashSet<>();
    QueryParamEntry queryParametersEntry = createQueryParameters(em, participatingQueries, queryStrings,
            querySpaces);
    QueryParameters queryParameters = queryParametersEntry.queryParameters;

    QueryPlanCacheKey cacheKey = createCacheKey(queryStrings, firstResult, maxResults);
    CacheEntry<HQLQueryPlan> queryPlanEntry = getQueryPlan(sfi, query, cacheKey);
    HQLQueryPlan queryPlan = queryPlanEntry.getValue();

    if (!queryPlanEntry.isFromCache()) {
        prepareQueryPlan(queryPlan, queryParametersEntry.specifications, finalSql, session, baseQuery, true,
                dbmsDialect);
        queryPlan = putQueryPlanIfAbsent(sfi, cacheKey, queryPlan);
    }

    autoFlush(querySpaces, session);

    if (queryPlan.getReturnMetadata() == null) {
        return hibernateAccess.performExecuteUpdate(queryPlan, session, queryParameters);
    }

    boolean caseInsensitive = !Boolean.valueOf(serviceProvider.getService(ConfigurationSource.class)
            .getProperty("com.blazebit.persistence.returning_clause_case_sensitive"));
    String exampleQuerySql = queryPlan.getSqlStrings()[0];
    String[][] returningColumns = getReturningColumns(caseInsensitive, exampleQuerySql);
    int[] returningColumnTypes = dbmsDialect.needsReturningSqlTypes() ? getReturningColumnTypes(queryPlan, sfi)
            : null;

    try {
        @SuppressWarnings("unchecked")
        List<Object> results = hibernateAccess.performList(queryPlan,
                wrapSession(session, dbmsDialect, returningColumns, returningColumnTypes, null),
                queryParameters);

        if (results.size() != 1) {
            throw new IllegalArgumentException("Expected size 1 but was: " + results.size());
        }

        Number count = (Number) results.get(0);
        return count.intValue();
    } catch (QueryExecutionRequestException he) {
        LOG.severe("Could not execute the following SQL query: " + finalSql);
        throw new IllegalStateException(he);
    } catch (TypeMismatchException e) {
        LOG.severe("Could not execute the following SQL query: " + finalSql);
        throw new IllegalArgumentException(e);
    } catch (HibernateException he) {
        LOG.severe("Could not execute the following SQL query: " + finalSql);
        hibernateAccess.throwPersistenceException(em, he);
        return 0;
    }
}

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public ReturningResult<Object[]> executeReturning(com.blazebit.persistence.spi.ServiceProvider serviceProvider,
        List<Query> participatingQueries, Query modificationBaseQuery, Query exampleQuery, String sqlOverride) {
    DbmsDialect dbmsDialect = serviceProvider.getService(DbmsDialect.class);
    EntityManager em = serviceProvider.getService(EntityManager.class);
    SessionImplementor session = em.unwrap(SessionImplementor.class);
    SessionFactoryImplementor sfi = session.getFactory();

    if (session.isClosed()) {
        throw new PersistenceException("Entity manager is closed!");
    }/* w w w  .jav a2 s .  com*/

    // Create combined query parameters
    List<String> queryStrings = new ArrayList<>(participatingQueries.size());
    Set<String> querySpaces = new HashSet<>();
    QueryParamEntry queryParametersEntry = createQueryParameters(em, participatingQueries, queryStrings,
            querySpaces);
    QueryParameters queryParameters = queryParametersEntry.queryParameters;

    // Create plan for example query
    QueryPlanCacheKey cacheKey = createCacheKey(queryStrings);
    CacheEntry<HQLQueryPlan> queryPlanEntry = getQueryPlan(sfi, exampleQuery, cacheKey);
    HQLQueryPlan queryPlan = queryPlanEntry.getValue();
    String exampleQuerySql = queryPlan.getSqlStrings()[0];

    StringBuilder sqlSb = new StringBuilder(sqlOverride.length() + 100);
    sqlSb.append(sqlOverride);

    boolean caseInsensitive = !Boolean.valueOf(serviceProvider.getService(ConfigurationSource.class)
            .getProperty("com.blazebit.persistence.returning_clause_case_sensitive"));
    String[][] returningColumns = getReturningColumns(caseInsensitive, exampleQuerySql);
    int[] returningColumnTypes = dbmsDialect.needsReturningSqlTypes() ? getReturningColumnTypes(queryPlan, sfi)
            : null;
    String finalSql = sqlSb.toString();

    try {
        HibernateReturningResult<Object[]> returningResult = new HibernateReturningResult<Object[]>();
        if (!queryPlanEntry.isFromCache()) {
            prepareQueryPlan(queryPlan, queryParametersEntry.specifications, finalSql, session,
                    modificationBaseQuery, true, dbmsDialect);
            queryPlan = putQueryPlanIfAbsent(sfi, cacheKey, queryPlan);
        }

        if (queryPlan.getTranslators().length > 1) {
            throw new IllegalArgumentException("No support for multiple translators yet!");
        }

        QueryTranslator queryTranslator = queryPlan.getTranslators()[0];

        // If the DBMS doesn't support inclusion of cascading deletes in a with clause, we have to execute them manually
        StatementExecutor executor = getExecutor(queryTranslator, session, modificationBaseQuery);
        List<String> originalDeletes = Collections.emptyList();

        if (executor != null && executor instanceof DeleteExecutor) {
            originalDeletes = getField(executor, "deletes");
        }

        // Extract query loader for native listing
        QueryLoader queryLoader = getField(queryTranslator, "queryLoader");

        // Do the native list operation with custom session and combined parameters

        /*
         * NATIVE LIST START
         */
        hibernateAccess.checkTransactionSynchStatus(session);
        queryParameters.validateParameters();
        autoFlush(querySpaces, session);

        List<Object[]> results = Collections.EMPTY_LIST;
        boolean success = false;

        try {
            for (String delete : originalDeletes) {
                hibernateAccess.doExecute(executor, delete, queryParameters, session,
                        queryParametersEntry.specifications);
            }

            results = hibernateAccess.list(queryLoader,
                    wrapSession(session, dbmsDialect, returningColumns, returningColumnTypes, returningResult),
                    queryParameters);
            success = true;
        } catch (QueryExecutionRequestException he) {
            LOG.severe("Could not execute the following SQL query: " + finalSql);
            throw new IllegalStateException(he);
        } catch (TypeMismatchException e) {
            LOG.severe("Could not execute the following SQL query: " + finalSql);
            throw new IllegalArgumentException(e);
        } catch (HibernateException he) {
            LOG.severe("Could not execute the following SQL query: " + finalSql);
            throw hibernateAccess.convert(em, he);
        } finally {
            hibernateAccess.afterTransaction(session, success);
        }
        /*
         * NATIVE LIST END
         */

        returningResult.setResultList(results);
        return returningResult;
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }
}

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

public void autoFlush(Set<String> querySpaces, SessionImplementor sessionImplementor) {
    AutoFlushEvent event = new AutoFlushEvent(querySpaces, (EventSource) sessionImplementor);
    for (AutoFlushEventListener listener : sessionImplementor.getFactory().getServiceRegistry()
            .getService(EventListenerRegistry.class).getEventListenerGroup(EventType.AUTO_FLUSH).listeners()) {
        listener.onAutoFlush(event);/*www .j av  a 2  s.co m*/
    }
}

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

private List<QueryParamEntry> getQueryParamEntries(EntityManager em, List<Query> queries,
        Set<String> querySpaces) {
    SessionImplementor session = em.unwrap(SessionImplementor.class);
    SessionFactoryImplementor sfi = session.getFactory();
    List<QueryParamEntry> result = new ArrayList<QueryParamEntry>(queries.size());
    Deque<Query> queryQueue = new LinkedList<Query>(queries);

    while (queryQueue.size() > 0) {
        Query q = queryQueue.remove();
        if (q instanceof CteQueryWrapper) {
            List<Query> participatingQueries = ((CteQueryWrapper) q).getParticipatingQueries();
            for (int i = participatingQueries.size() - 1; i > -1; i--) {
                queryQueue.addFirst(participatingQueries.get(i));
            }//from   w  ww . j a va  2s . c o m
            continue;
        }

        org.hibernate.Query hibernateQuery = q.unwrap(org.hibernate.Query.class);

        Map<String, TypedValue> namedParams = new HashMap<String, TypedValue>(
                hibernateAccess.getNamedParams(hibernateQuery));
        String queryString = hibernateAccess.expandParameterLists(session, hibernateQuery, namedParams);

        HQLQueryPlan queryPlan = sfi.getQueryPlanCache().getHQLQueryPlan(queryString, false,
                Collections.EMPTY_MAP);

        if (queryPlan.getTranslators().length > 1) {
            throw new IllegalArgumentException("No support for multiple translators yet!");
        }

        querySpaces.addAll(queryPlan.getQuerySpaces());

        QueryTranslator queryTranslator = queryPlan.getTranslators()[0];
        QueryParameters queryParameters;
        List<ParameterSpecification> specifications;

        try {
            queryParameters = hibernateAccess.getQueryParameters(hibernateQuery, namedParams);
            specifications = getField(queryTranslator, "collectedParameterSpecifications");

            // This only happens for modification queries
            if (specifications == null) {
                StatementExecutor executor = getStatementExecutor(queryTranslator);
                if (!(executor instanceof BasicExecutor)) {
                    throw new IllegalArgumentException(
                            "Using polymorphic deletes/updates with CTEs is not yet supported");
                }
                specifications = getField(executor, "parameterSpecifications");
            }
        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }

        result.add(new QueryParamEntry(queryString, queryParameters, specifications));
    }

    return result;
}

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

private void prepareQueryPlan(HQLQueryPlan queryPlan, List<ParameterSpecification> queryParameterSpecifications,
        String finalSql, SessionImplementor session, Query modificationBaseQuery, boolean isModification,
        DbmsDialect dbmsDialect) {/*from   w ww . j  ava  2 s. com*/
    try {
        if (queryPlan.getTranslators().length > 1) {
            throw new IllegalArgumentException("No support for multiple translators yet!");
        }

        QueryTranslator queryTranslator = queryPlan.getTranslators()[0];
        // Override the sql in the query plan
        setField(queryTranslator, "sql", finalSql);

        QueryLoader queryLoader = getField(queryTranslator, "queryLoader");
        // INSERT statement does not have a query loader
        if (queryLoader != null) {
            setField(queryLoader, "factory",
                    hibernateAccess.wrapSessionFactory(queryLoader.getFactory(), dbmsDialect));
        }

        // Modification queries keep the sql in the executor
        StatementExecutor executor = null;

        Field statementExectuor = null;
        boolean madeAccessible = false;

        try {
            statementExectuor = ReflectionUtils.getField(queryTranslator.getClass(), "statementExecutor");
            madeAccessible = !statementExectuor.isAccessible();

            if (madeAccessible) {
                statementExectuor.setAccessible(true);
            }

            executor = (StatementExecutor) statementExectuor.get(queryTranslator);

            if (executor == null && isModification) {
                // We have to set an executor
                org.hibernate.Query lastHibernateQuery = modificationBaseQuery
                        .unwrap(org.hibernate.Query.class);

                Map<String, TypedValue> namedParams = new HashMap<String, TypedValue>(
                        hibernateAccess.getNamedParams(lastHibernateQuery));
                String queryString = hibernateAccess.expandParameterLists(session, lastHibernateQuery,
                        namedParams);

                // Extract the executor from the last query which is the actual main query
                HQLQueryPlan lastQueryPlan = session.getFactory().getQueryPlanCache()
                        .getHQLQueryPlan(queryString, false, Collections.EMPTY_MAP);
                if (lastQueryPlan.getTranslators().length > 1) {
                    throw new IllegalArgumentException("No support for multiple translators yet!");
                }
                QueryTranslator lastQueryTranslator = lastQueryPlan.getTranslators()[0];
                executor = (StatementExecutor) statementExectuor.get(lastQueryTranslator);
                // Now we use this executor for our example query
                statementExectuor.set(queryTranslator, executor);
            }
        } finally {
            if (madeAccessible) {
                statementExectuor.setAccessible(false);
            }
        }

        if (executor != null) {
            setField(executor, "sql", finalSql);
            setField(executor, BasicExecutor.class, "parameterSpecifications", queryParameterSpecifications);

            if (executor instanceof DeleteExecutor) {
                int withIndex;
                if (dbmsDialect.supportsModificationQueryInWithClause()) {
                    setField(executor, "deletes", new ArrayList<String>());
                } else if ((withIndex = finalSql.indexOf("with ")) != -1) {
                    int end = getCTEEnd(finalSql, withIndex);

                    List<String> originalDeletes = getField(executor, "deletes");
                    int maxLength = 0;

                    for (String s : originalDeletes) {
                        maxLength = Math.max(maxLength, s.length());
                    }

                    List<String> deletes = new ArrayList<String>(originalDeletes.size());
                    StringBuilder newSb = new StringBuilder(end + maxLength);
                    // Prefix properly with cte
                    StringBuilder withClauseSb = new StringBuilder(end - withIndex);
                    withClauseSb.append(finalSql, withIndex, end);

                    for (String s : originalDeletes) {
                        // TODO: The strings should also receive the simple CTE name instead of the complex one
                        newSb.append(s);
                        dbmsDialect.appendExtendedSql(newSb, DbmsStatementType.DELETE, false, false,
                                withClauseSb, null, null, null, null);
                        deletes.add(newSb.toString());
                        newSb.setLength(0);
                    }

                    setField(executor, "deletes", deletes);
                }
            }
        }

        // Prepare queryTranslator for aggregated parameters
        ParameterTranslations translations = hibernateAccess
                .createParameterTranslations(queryParameterSpecifications);
        setField(queryTranslator, "paramTranslations", translations);
        setField(queryTranslator, "collectedParameterSpecifications", queryParameterSpecifications);
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }
}

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

private StatementExecutor getExecutor(QueryTranslator queryTranslator, SessionImplementor session,
        Query lastQuery) {// ww  w .  j  ava 2  s .c  o  m
    // Modification queries keep the sql in the executor
    StatementExecutor executor = null;

    Field statementExectuor = null;
    boolean madeAccessible = false;

    try {
        statementExectuor = ReflectionUtils.getField(queryTranslator.getClass(), "statementExecutor");
        madeAccessible = !statementExectuor.isAccessible();

        if (madeAccessible) {
            statementExectuor.setAccessible(true);
        }

        executor = (StatementExecutor) statementExectuor.get(queryTranslator);

        if (executor == null) {
            // We have to set an executor
            org.hibernate.Query lastHibernateQuery = lastQuery.unwrap(org.hibernate.Query.class);

            Map<String, TypedValue> namedParams = new HashMap<String, TypedValue>(
                    hibernateAccess.getNamedParams(lastHibernateQuery));
            String queryString = hibernateAccess.expandParameterLists(session, lastHibernateQuery, namedParams);

            // Extract the executor from the last query which is the actual main query
            HQLQueryPlan lastQueryPlan = session.getFactory().getQueryPlanCache().getHQLQueryPlan(queryString,
                    false, Collections.EMPTY_MAP);
            if (lastQueryPlan.getTranslators().length > 1) {
                throw new IllegalArgumentException("No support for multiple translators yet!");
            }
            QueryTranslator lastQueryTranslator = lastQueryPlan.getTranslators()[0];
            executor = (StatementExecutor) statementExectuor.get(lastQueryTranslator);
        }
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    } finally {
        if (madeAccessible) {
            statementExectuor.setAccessible(false);
        }
    }

    return executor;
}

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateJpaProvider.java

License:Apache License

@Override
public boolean containsEntity(EntityManager em, Class<?> entityClass, Object id) {
    SessionImplementor session = em.unwrap(SessionImplementor.class);
    EntityKey entityKey = session.generateEntityKey((Serializable) id,
            session.getFactory().getEntityPersister(entityClass.getName()));
    PersistenceContext pc = session.getPersistenceContext();
    return pc.getEntity(entityKey) != null || pc.getProxy(entityKey) != null;
}