Example usage for org.hibernate Session getSessionFactory

List of usage examples for org.hibernate Session getSessionFactory

Introduction

In this page you can find the example usage for org.hibernate Session getSessionFactory.

Prototype

SessionFactory getSessionFactory();

Source Link

Document

Get the session factory which created this session.

Usage

From source file:org.nextframework.persistence.SaveOrUpdateStrategy.java

License:Open Source License

private List<?> findItensToDelete(final String parentProperty, final Class<?> itemClass,
        final Collection<?> collection) {
    final List<?> toDelete = (List<?>) hibernateTemplate.execute(new HibernateCommand() {
        public Object doInHibernate(Session session) {

            // remover dessa lista os objetos transientes
            Collection<Object> itens = new ArrayList<Object>(
                    collection == null ? new ArrayList<Object>() : collection);
            for (Iterator<Object> iter = itens.iterator(); iter.hasNext();) {
                Object entity = iter.next();
                Serializable id = PersistenceUtils.getId(entity, hibernateTemplate.getSessionFactory());
                if (id == null) {
                    iter.remove();// w w w.j a va  2 s.com
                }
            }
            if (itens.size() == 0) {
                // se nao tiver itens remover os que estiverem no banco
                final String findQueryString = new StringBuilder().append("from ").append(itemClass.getName())
                        .append(" ").append(uncapitalize(itemClass.getSimpleName())).append(" where ")
                        .append(uncapitalize(itemClass.getSimpleName())).append('.').append(parentProperty)
                        .append(" = :").append(entity.getClass().getSimpleName()).toString();

                Query q = session.createQuery(findQueryString);
                q.setEntity(entity.getClass().getSimpleName(), entity);
                return q.list();
            } else {
                boolean compositeParentProperty = parentProperty.indexOf('.') > 0;
                if (compositeParentProperty) {
                    // remover apenas os que nao estao na lista
                    // when the property is composite.. 
                    // must load all details and find manually the ones to delete 
                    final String findQueryString = new StringBuilder().append("from ")
                            .append(itemClass.getName()).append(" ")
                            .append(uncapitalize(itemClass.getSimpleName())).append(" where ")
                            .append(uncapitalize(itemClass.getSimpleName())).append('.').append(parentProperty)
                            .append(" = :").append(entity.getClass().getSimpleName()).toString();

                    Query q = session.createQuery(findQueryString);
                    q.setEntity(entity.getClass().getSimpleName(), entity);
                    List<?> databaseItems = q.list();
                    return PersistenceUtils.removeFromCollectionUsingId(session.getSessionFactory(),
                            databaseItems, itens);
                } else {
                    // remover apenas os que nao estao na lista
                    final String findQueryString = new StringBuilder().append("from ")
                            .append(itemClass.getName()).append(" ")
                            .append(uncapitalize(itemClass.getSimpleName())).append(" where ")
                            .append(uncapitalize(itemClass.getSimpleName()))
                            .append(" not in (:collection)  and ")
                            .append(uncapitalize(itemClass.getSimpleName())).append('.').append(parentProperty)
                            .append(" = :").append(entity.getClass().getSimpleName()).toString();

                    Query q = session.createQuery(findQueryString);
                    q.setParameterList("collection", itens);
                    q.setEntity(entity.getClass().getSimpleName(), entity);
                    return q.list();
                }
            }

        }

    });
    return toDelete;
}

From source file:org.openvpms.component.business.dao.hibernate.im.lookup.LookupReplacer.java

License:Open Source License

/**
 * Executes an update query.//w ww.j a v  a 2  s .co  m
 * <p/>
 * If any updates are made, the second level caches associated with the persisent classes are also cleared.
 * <p/>
 * <strong>NOTE</strong>: There is a small window where the second level cache will not reflect the state of the
 * database.
 *
 * @param query             the update query
 * @param session           the hibernate session
 * @param persistentClasses the persistent classes affected by the update
 */
private void executeUpdate(Query query, final Session session, final Class... persistentClasses) {
    int updates = query.executeUpdate();
    if (updates != 0) {
        final SessionFactory factory = session.getSessionFactory();
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            // clear the cache when the transaction commits
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCompletion(int status) {
                    if (status == STATUS_COMMITTED) {
                        clearCaches(persistentClasses, factory);
                    }
                }
            });
        } else {
            clearCaches(persistentClasses, factory);
        }
    }
}

From source file:org.projectforge.database.xstream.HibernateXmlConverter.java

License:Open Source License

/**
 * @param writer//from w ww. j av a 2s  .  co m
 * @param includeHistory
 * @param session
 * @throws DataAccessException
 * @throws HibernateException
 */
private void writeObjects(final Writer writer, final boolean includeHistory, final Session session,
        final boolean preserveIds) throws DataAccessException, HibernateException {
    // Container fr die Objekte
    final List<Object> all = new ArrayList<Object>();
    final XStream stream = initXStream(session, true);
    final XStream defaultXStream = initXStream(session, false);

    session.flush();
    // Alles laden
    List<?> list = session.createQuery("select o from java.lang.Object o").setReadOnly(true).list();
    list = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
    final int size = list.size();
    log.info("Writing " + size + " objects");
    for (final Iterator<?> it = list.iterator(); it.hasNext();) {
        final Object obj = it.next();
        if (log.isDebugEnabled()) {
            log.debug("loaded object " + obj);
        }
        if ((obj instanceof HistoryEntry || obj instanceof PropertyDelta) && includeHistory == false) {
            continue;
        }
        Hibernate.initialize(obj);
        Class<?> targetClass = obj.getClass();
        while (Enhancer.isEnhanced(targetClass) == true) {
            targetClass = targetClass.getSuperclass();
        }
        final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass);
        if (classMetadata == null) {
            log.fatal("Can't init " + obj + " of type " + targetClass);
            continue;
        }
        // initalisierung des Objekts...
        defaultXStream.marshal(obj, new CompactWriter(new NullWriter()));

        if (preserveIds == false) {
            // Nun kann die ID gelscht werden
            classMetadata.setIdentifier(obj, null, EntityMode.POJO);
        }
        if (log.isDebugEnabled()) {
            log.debug("loading evicted object " + obj);
        }
        if (this.ignoreFromTopLevelListing.contains(targetClass) == false) {
            all.add(obj);
        }
    }
    // und schreiben
    try {
        writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
    } catch (final IOException ex) {
        // ignore, will fail on stream.marshal()
    }
    log.info("Wrote " + all.size() + " objects");
    final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy();
    stream.setMarshallingStrategy(marshallingStrategy);
    stream.marshal(all, new PrettyPrintWriter(writer));
}

From source file:org.projectforge.framework.persistence.xstream.HibernateXmlConverter.java

License:Open Source License

/**
 * @param writer/*from  w  ww .  jav  a  2 s  .  c o  m*/
 * @param includeHistory
 * @param session
 * @throws DataAccessException
 * @throws HibernateException
 */
private void writeObjects(final Writer writer, final boolean includeHistory, final Session session,
        final boolean preserveIds) throws DataAccessException, HibernateException {
    // Container fr die Objekte
    final List<Object> all = new ArrayList<Object>();
    final XStream stream = initXStream(session, true);
    final XStream defaultXStream = initXStream(session, false);

    session.flush();
    // Alles laden
    //    final List<Class<?>> entities = new ArrayList<Class<?>>();
    final List<Class<?>> entities = PfEmgrFactory.get().getMetadataRepository().getTableEntities().stream()
            .map((e) -> e.getJavaType()).collect(Collectors.toList());
    //    entities.addAll(HibernateEntities.instance().getOrderedEntities());
    //    entities.addAll(HibernateEntities.instance().getOrderedHistoryEntities());
    for (final Class<?> entityClass : entities) {
        final String entitySimpleName = entityClass.getSimpleName();
        final String entityType = entityClass.getName();

        if (includeHistory == false
                && entityType.startsWith("org.projectforge.framework.persistence.history.entities.") == true) {
            // Skip history entries.
            continue;
        }
        List<?> list = session.createQuery("select o from " + entityType + " o").setReadOnly(true).list();
        list = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
        final int size = list.size();
        log.info("Writing " + size + " objects");
        for (final Iterator<?> it = list.iterator(); it.hasNext();) {
            final Object obj = it.next();
            if (log.isDebugEnabled()) {
                log.debug("loaded object " + obj);
            }
            Hibernate.initialize(obj);
            final Class<?> targetClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
            final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass);
            if (classMetadata == null) {
                log.fatal("Can't init " + obj + " of type " + targetClass);
                continue;
            }
            // initalisierung des Objekts...
            defaultXStream.marshal(obj, new CompactWriter(new NullWriter()));

            if (preserveIds == false) {
                // Nun kann die ID gelscht werden
                HibernateCompatUtils.setClassMetaDataSetIdentifier(classMetadata, obj, EntityMode.POJO);
            }
            if (log.isDebugEnabled()) {
                log.debug("loading evicted object " + obj);
            }
            if (this.ignoreFromTopLevelListing.contains(targetClass) == false) {
                all.add(obj);
            }
        }
    }
    // und schreiben
    try {
        writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
    } catch (final IOException ex) {
        // ignore, will fail on stream.marshal()
    }
    log.info("Wrote " + all.size() + " objects");
    final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy();
    stream.setMarshallingStrategy(marshallingStrategy);
    stream.marshal(all, new PrettyPrintWriter(writer));
}

From source file:org.rhq.core.domain.server.PersistenceUtility.java

License:Open Source License

public static Statistics getStatisticsService(EntityManager entityManager, MBeanServer server) {
    Session hibernateSession = PersistenceUtility.getHibernateSession(entityManager);
    SessionFactory hibernateSessionFactory = hibernateSession.getSessionFactory();
    Statistics hibernateStatistics = hibernateSessionFactory.getStatistics();
    return hibernateStatistics;
}

From source file:org.rhq.core.domain.server.PersistenceUtility.java

License:Open Source License

private static SessionFactoryImplementor getHibernateSessionFactoryImplementor(EntityManager entityManager) {
    Session session = getHibernateSession(entityManager);
    SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) session.getSessionFactory();
    return sessionFactory;
}

From source file:org.rhq.core.domain.test.QueryAllTest.java

License:Open Source License

/**
 * Run those NamedQueries that do not need parameters to be set.
 *
 * @throws Exception/*from   w w w . j  a va  2 s  .  c  om*/
 */
@Test(groups = "integration.ejb3")
public void testQueryAllSimpleNamedQueries() throws Exception {
    Object o = em.getDelegate();
    Class del = o.getClass();
    System.out.println("Delegate is " + del.toString());
    Session sess = (Session) o; // Hibernate Session in JBoss
    sessionFactory = (SessionFactoryImplementor) sess.getSessionFactory();
    Map cMeta = sessionFactory.getAllClassMetadata();

    List<String> configuredEntities = Arrays.asList(ENTITY_NAMES);

    Collection<ClassMetadata> metas = cMeta.values();

    try {
        for (ClassMetadata cm : metas) {
            String entity = cm.getEntityName();
            String shortName = entity.substring(entity.lastIndexOf(".") + 1);

            // Skip entites that are not in above list
            if (!configuredEntities.contains(shortName)) {
                //System.out.println("== Skipping " + entity );
                continue;
            }

            System.out.println("Testing queries for: " + shortName);
            List<NamedQuery> nqs = getNamedQueriesForEntity(entity);
            for (NamedQuery nq : nqs) {
                boolean hasId;

                // Skip those with non-ID parameters for now, as we dont not
                // know how to obtain the parameters from Hibernate, as
                // they are not set when parsing the NamedQuery annotation :-(
                // we can just give bogus ID numbers by param indexes.
                // I would like to use the regex (nq.query().matches(".*:(?!([a-zA-Z]*[iI]d)[ =]).*"))
                // to match anything like :*id or :*Id but too hard to think how to
                // set the parameter names.  so for now, just look for :id (ignore :ids too)
                if (nq.query().matches(".*:(?!(id([^s]|$))).*")) {
                    continue;
                }

                hasId = nq.query().contains(":id");

                if (nq.query().contains("UPDATE ") || nq.query().contains("update ")) {
                    continue;
                }

                if (nq.query().contains("DELETE ") || nq.query().contains("delete ")) {
                    continue;
                }

                if (nq.query().contains("INSERT ") || nq.query().contains("insert ")) {
                    continue;
                }

                try {
                    //System.out.print("  == query " + nq.name());
                    Query query = em.createNamedQuery(nq.name());

                    // TODO set parameters here
                    // fillParameters(query, nq);
                    // if we have some ID params, just set them to something
                    if (hasId) {
                        query.setParameter("id", Integer.valueOf(0));
                        //System.out.println("Query with ID parameter: " + nq.query());
                    }

                    query.setMaxResults(5);
                    Collection results = query.getResultList();
                    System.out.println("   " + nq.name() + "==> #results: " + results.size());
                } catch (Throwable t) {
                    assert false : "Failed to query named query " + nq.name() + ": "
                            + ThrowableUtil.getAllMessages(t, true);
                }
            }
        }
    } catch (NoResultException nre) {
        System.out.println("  ==> no results found");
    }
}

From source file:org.rhq.server.metrics.migrator.datasources.ExistingDataJPABulkExportSource.java

License:Open Source License

protected void exportExistingData() throws Exception {
    BufferedWriter fileWriter = null;
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;/*from w  w  w  .j av a2  s.c  o  m*/
    try {
        fileWriter = new BufferedWriter(new FileWriter(getExistingDataFile()), IO_BUFFER_SIZE);
        Session session = (Session) this.entityManager.getDelegate();
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
        ConnectionProvider cp = sfi.getConnectionProvider();
        connection = cp.getConnection();
        statement = connection.prepareStatement(this.selectNativeQuery);
        resultSet = statement.executeQuery();
        int columnCount = resultSet.getMetaData().getColumnCount();
        while (resultSet.next()) {
            for (int i = 1; i < columnCount + 1; i++) {
                if (i > 1) {
                    fileWriter.write(DELIMITER);
                }
                fileWriter.write(resultSet.getString(i));
            }
            fileWriter.write("\n");
        }
    } finally {
        StreamUtil.safeClose(fileWriter);
        JDBCUtil.safeClose(connection, statement, resultSet);
    }
}

From source file:org.rhq.server.metrics.migrator.datasources.ExistingPostgresDataBulkExportSource.java

License:Open Source License

protected void exportExistingData() throws Exception {
    BufferedWriter fileWriter = null;
    Connection connection = null;
    try {//from  w  w  w  .  j ava2 s.c  o  m
        fileWriter = new BufferedWriter(new FileWriter(getExistingDataFile()), IO_BUFFER_SIZE);
        Session session = (Session) entityManager.getDelegate();
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
        ConnectionProvider cp = sfi.getConnectionProvider();
        connection = cp.getConnection();
        CopyManager copyManager = new CopyManager((BaseConnection) connection);

        if (maxResults > 0) {
            copyManager.copyOut("COPY (" + selectNativeQuery + " LIMIT " + maxResults
                    + ") TO STDOUT WITH DELIMITER '" + DELIMITER + "'", fileWriter);
        } else {
            copyManager.copyOut("COPY (" + selectNativeQuery + ") TO STDOUT WITH DELIMITER '" + DELIMITER + "'",
                    fileWriter);
        }
    } finally {
        StreamUtil.safeClose(fileWriter);
        JDBCUtil.safeClose(connection);
    }
}

From source file:org.riotfamily.common.hibernate.HibernateUtils.java

License:Apache License

@SuppressWarnings("unchecked")
public static <T> T get(Session session, Class<T> beanClass, String id) {
    SessionFactory sf = session.getSessionFactory();
    Serializable serialId = convertId(beanClass, id, sf);
    return (T) session.get(beanClass, serialId);
}