Example usage for org.hibernate SessionFactory getAllClassMetadata

List of usage examples for org.hibernate SessionFactory getAllClassMetadata

Introduction

In this page you can find the example usage for org.hibernate SessionFactory getAllClassMetadata.

Prototype

@Deprecated
Map<String, ClassMetadata> getAllClassMetadata();

Source Link

Document

Retrieve the ClassMetadata for all mapped entities.

Usage

From source file:org.beangle.commons.orm.hibernate.internal.HibernateEntityContext.java

License:Open Source License

public void initFrom(SessionFactory sessionFactory) {
    if (null != sessionFactory && entityTypes.isEmpty()) {
        Stopwatch watch = new Stopwatch().start();
        Map<String, ClassMetadata> classMetadatas = sessionFactory.getAllClassMetadata();
        for (Iterator<ClassMetadata> iter = classMetadatas.values().iterator(); iter.hasNext();) {
            ClassMetadata cm = (ClassMetadata) iter.next();
            buildEntityType(sessionFactory, cm.getEntityName());
        }//from w  w w  . jav  a 2s .c om
        logger.info("Find {} entities,{} collections from hibernate in {}",
                new Object[] { entityTypes.size(), collectionTypes.size(), watch });
        if (logger.isDebugEnabled()) {
            loggerTypeInfo();
        }
        collectionTypes.clear();
    }
}

From source file:org.beangle.model.persist.hibernate.HibernateEntityContext.java

License:Open Source License

public void initFrom(SessionFactory sessionFactory) {
    if (null != sessionFactory && entityTypes.isEmpty()) {
        StopWatch watch = new StopWatch();
        watch.start();//  w w w.j a  v  a2s .  c  o  m
        Map<String, ClassMetadata> classMetadatas = sessionFactory.getAllClassMetadata();
        for (Iterator<ClassMetadata> iter = classMetadatas.values().iterator(); iter.hasNext();) {
            ClassMetadata cm = (ClassMetadata) iter.next();
            buildEntityType(sessionFactory, cm.getEntityName());
        }
        logger.info("Find {} entities,{} collections from hibernate in {} ms",
                new Object[] { entityTypes.size(), collectionTypes.size(), watch.getTime() });
        if (logger.isDebugEnabled()) {
            loggerTypeInfo();
        }
        collectionTypes.clear();
    }
}

From source file:org.beangle.orm.hibernate.internal.HibernateEntityContext.java

License:Open Source License

/**
 * Build context from session factory/*from   w  w w  .j  a va 2 s  .co  m*/
 */
public void initFrom(SessionFactory sessionFactory) {
    Assert.notNull(sessionFactory);
    Stopwatch watch = new Stopwatch().start();
    Map<String, ClassMetadata> classMetadatas = sessionFactory.getAllClassMetadata();
    for (Iterator<ClassMetadata> iter = classMetadatas.values().iterator(); iter.hasNext();) {
        ClassMetadata cm = (ClassMetadata) iter.next();
        buildEntityType(sessionFactory, cm.getEntityName());
    }
    logger.info("Find {} entities,{} collections from hibernate in {}",
            new Object[] { entityTypes.size(), collectionTypes.size(), watch });
    if (logger.isDebugEnabled())
        loggerTypeInfo();
    collectionTypes.clear();
}

From source file:org.broadleafcommerce.common.persistence.SequenceGeneratorCorruptionDetection.java

License:Apache License

@Override
@Transactional("blTransactionManager")
public void onApplicationEvent(ContextRefreshedEvent event) {
    if (detectSequenceGeneratorInconsistencies) {
        SessionFactory sessionFactory = ((HibernateEntityManager) em).getSession().getSessionFactory();
        for (Object item : sessionFactory.getAllClassMetadata().values()) {
            ClassMetadata metadata = (ClassMetadata) item;
            String idProperty = metadata.getIdentifierPropertyName();
            Class<?> mappedClass = metadata.getMappedClass();
            Field idField;/* ww  w  .ja  v a2s .c  o m*/
            try {
                idField = mappedClass.getDeclaredField(idProperty);
            } catch (NoSuchFieldException e) {
                continue;
            }
            idField.setAccessible(true);
            GenericGenerator genericAnnot = idField.getAnnotation(GenericGenerator.class);
            TableGenerator tableAnnot = idField.getAnnotation(TableGenerator.class);
            String segmentValue = null;
            String tableName = null;
            String segmentColumnName = null;
            String valueColumnName = null;
            if (genericAnnot != null && genericAnnot.strategy()
                    .equals("org.broadleafcommerce.common.persistence.IdOverrideTableGenerator")) {
                //This is a BLC style ID generator
                for (Parameter param : genericAnnot.parameters()) {
                    if (param.name().equals("segment_value")) {
                        segmentValue = param.value();
                    }
                    if (param.name().equals("table_name")) {
                        tableName = param.value();
                    }
                    if (param.name().equals("segment_column_name")) {
                        segmentColumnName = param.value();
                    }
                    if (param.name().equals("value_column_name")) {
                        valueColumnName = param.value();
                    }
                }
            } else if (tableAnnot != null) {
                //This is a traditional Hibernate generator
                segmentValue = tableAnnot.pkColumnValue();
                tableName = tableAnnot.table();
                segmentColumnName = tableAnnot.pkColumnName();
                valueColumnName = tableAnnot.valueColumnName();
            }
            if (!StringUtils.isEmpty(segmentValue) && !StringUtils.isEmpty(tableName)
                    && !StringUtils.isEmpty(segmentColumnName) && !StringUtils.isEmpty(valueColumnName)) {
                StringBuilder sb2 = new StringBuilder();
                sb2.append("select ");
                sb2.append(valueColumnName);
                sb2.append(" from ");
                if (!tableName.contains(".") && !StringUtils.isEmpty(defaultSchemaSequenceGenerator)) {
                    sb2.append(defaultSchemaSequenceGenerator);
                    sb2.append(".");
                }
                sb2.append(tableName);
                sb2.append(" where ");
                sb2.append(segmentColumnName);
                sb2.append(" = '");
                sb2.append(segmentValue);
                sb2.append("'");

                List results2 = em.createNativeQuery(sb2.toString()).getResultList();
                if (results2 != null && !results2.isEmpty() && results2.get(0) != null) {
                    Long maxSequenceId = ((Number) results2.get(0)).longValue();

                    LOG.info("Detecting id sequence state between " + mappedClass.getName() + " and "
                            + segmentValue + " in " + tableName);

                    StringBuilder sb = new StringBuilder();
                    sb.append("select max(");
                    sb.append(idField.getName());
                    sb.append(") from ");
                    sb.append(mappedClass.getName());
                    sb.append(" entity");
                    List results = em.createQuery(sb.toString()).getResultList();
                    if (results != null && !results.isEmpty() && results.get(0) != null) {
                        Long maxEntityId = (Long) results.get(0);
                        if (maxEntityId > maxSequenceId) {
                            if (automaticallyCorrectInconsistencies) {
                                StringBuilder sb3 = new StringBuilder();
                                sb3.append("update ");
                                if (!tableName.contains(".")
                                        && !StringUtils.isEmpty(defaultSchemaSequenceGenerator)) {
                                    sb2.append(defaultSchemaSequenceGenerator);
                                    sb2.append(".");
                                }
                                sb3.append(tableName);
                                sb3.append(" set ");
                                sb3.append(valueColumnName);
                                sb3.append(" = ");
                                sb3.append(String.valueOf(maxEntityId + 10));
                                sb3.append(" where ");
                                sb3.append(segmentColumnName);
                                sb3.append(" = '");
                                sb3.append(segmentValue);
                                sb3.append("'");

                                int response = em.createNativeQuery(sb3.toString()).executeUpdate();
                                if (response <= 0) {
                                    throw new RuntimeException("Unable to update " + tableName
                                            + " with the sequence generator id for " + segmentValue);
                                }
                            } else {
                                String reason = "A data inconsistency has been detected between the "
                                        + tableName
                                        + " table and one or more entity tables for which it manages current max primary key values.\n"
                                        + "The inconsistency was detected between the managed class ("
                                        + mappedClass.getName() + ") and the identifier (" + segmentValue
                                        + ") in " + tableName + ". Broadleaf\n"
                                        + "has stopped startup of the application in order to allow you to resolve the issue and avoid possible data corruption. If you wish to disable this detection, you may\n"
                                        + "set the 'detect.sequence.generator.inconsistencies' property to false in your application's common.properties or common-shared.properties. If you would like for this component\n"
                                        + "to autocorrect these problems by setting the sequence generator value to a value greater than the max entity id, then set the 'auto.correct.sequence.generator.inconsistencies'\n"
                                        + "property to true in your application's common.properties or common-shared.properties. If you would like to provide a default schema to be used to qualify table names used in the\n"
                                        + "queries for this detection, set the 'default.schema.sequence.generator' property in your application's common.properties or common-shared.properties. Also, if you are upgrading\n"
                                        + "from 1.6 or below, please refer to http://docs.broadleafcommerce.org/current/1.6-to-2.0-Migration.html for important information regarding migrating your SEQUENCE_GENERATOR table.";
                                LOG.error("Broadleaf Commerce failed to start", new RuntimeException(reason));
                                System.exit(1);
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.broadleafcommerce.common.util.dao.DynamicDaoHelperImpl.java

License:Apache License

@Override
public Class<?>[] getAllPolymorphicEntitiesFromCeiling(Class<?> ceilingClass, SessionFactory sessionFactory,
        boolean includeUnqualifiedPolymorphicEntities, boolean useCache) {
    ceilingClass = getNonProxyImplementationClassIfNecessary(ceilingClass);
    Class<?>[] cache = null;
    synchronized (LOCK_OBJECT) {
        if (useCache) {
            if (includeUnqualifiedPolymorphicEntities) {
                cache = POLYMORPHIC_ENTITY_CACHE.get(ceilingClass);
            } else {
                cache = POLYMORPHIC_ENTITY_CACHE_WO_EXCLUSIONS.get(ceilingClass);
            }// w  w w  . j a  va 2s.co m
        }
        if (cache == null) {
            List<Class<?>> entities = new ArrayList<Class<?>>();
            for (Object item : sessionFactory.getAllClassMetadata().values()) {
                ClassMetadata metadata = (ClassMetadata) item;
                Class<?> mappedClass = metadata.getMappedClass();
                if (mappedClass != null && ceilingClass.isAssignableFrom(mappedClass)) {
                    entities.add(mappedClass);
                }
            }
            Class<?>[] sortedEntities = sortEntities(ceilingClass, entities);

            List<Class<?>> filteredSortedEntities = new ArrayList<Class<?>>();

            for (int i = 0; i < sortedEntities.length; i++) {
                Class<?> item = sortedEntities[i];
                if (includeUnqualifiedPolymorphicEntities) {
                    filteredSortedEntities.add(sortedEntities[i]);
                } else {
                    if (isExcludeClassFromPolymorphism(item)) {
                        continue;
                    } else {
                        filteredSortedEntities.add(sortedEntities[i]);
                    }
                }
            }

            Class<?>[] filteredEntities = new Class<?>[filteredSortedEntities.size()];
            filteredEntities = filteredSortedEntities.toArray(filteredEntities);
            cache = filteredEntities;
            if (includeUnqualifiedPolymorphicEntities) {
                POLYMORPHIC_ENTITY_CACHE.put(ceilingClass, filteredEntities);
            } else {
                POLYMORPHIC_ENTITY_CACHE_WO_EXCLUSIONS.put(ceilingClass, filteredEntities);
            }
        }
    }

    return cache;
}

From source file:org.brushingbits.jnap.persistence.factory.DaoFactoryPostProcessor.java

License:Apache License

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    Assert.isAssignable(DefaultListableBeanFactory.class, registry.getClass(),
            "The DaoFactoryPostProcessor only works within a DefaultListableBeanFactory capable"
                    + "BeanFactory, your BeanDefinitionRegistry is " + registry.getClass());
    final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) registry;

    // get already defined beans of type Dao
    final Set<Class<? extends PersistentModel>> alreadyDefinedDaos = new HashSet<Class<? extends PersistentModel>>();
    for (String beanName : beanFactory.getBeanNamesForType(Dao.class, true, false)) {
        Dao<? extends PersistentModel> dao = beanFactory.getBean(beanName, Dao.class);
        alreadyDefinedDaos.add(dao.getEntityClass());
    }/*from ww w.java 2 s .c o  m*/

    for (String sessionFactoryName : beanFactory.getBeanNamesForType(SessionFactory.class)) {
        final SessionFactory sessionFactory = beanFactory.getBean(sessionFactoryName, SessionFactory.class);
        Map<String, ClassMetadata> entitiesMetadata = sessionFactory.getAllClassMetadata();
        for (ClassMetadata entityMetadata : entitiesMetadata.values()) {
            Class<? extends PersistentModel> entityClass = entityMetadata.getMappedClass(EntityMode.POJO);
            if (entityClass != null && !alreadyDefinedDaos.contains(entityClass)) {
                String daoName = entityClass.getSimpleName() + "Dao";
                daoName = Character.toLowerCase(daoName.charAt(0)) + daoName.substring(1);
                beanFactory.registerBeanDefinition(daoName, createDaoDefinition(entityClass, sessionFactory));
            }
        }
    }
}

From source file:org.castafiore.wfs.futil.java

License:Open Source License

public static List<SimpleKeyValuePair> getEntityTypes() {
    List<SimpleKeyValuePair> result = new ArrayList<SimpleKeyValuePair>();
    try {/* w  w  w .  j  a va  2  s  .c o  m*/
        SessionFactory factory = BaseSpringUtil.getBeanOfType(SessionFactory.class);
        Object[] clss = factory.getAllClassMetadata().keySet().toArray();
        for (int index = 0; index < clss.length; index++) {
            try {
                Object o = Thread.currentThread().getContextClassLoader().loadClass(clss[index].toString())
                        .newInstance();
                if (o instanceof File) {
                    SimpleKeyValuePair kv = new SimpleKeyValuePair(clss[index].toString(),
                            StringUtil.split(clss[index].toString(),
                                    ".")[StringUtil.split(clss[index].toString(), ".").length - 1]);
                    result.add(kv);
                }
            } catch (Exception e) {

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

License:Apache License

public static void configureHibernateDomainClasses(SessionFactory sessionFactory,
        GrailsApplication application) {
    Map<String, GrailsDomainClass> hibernateDomainClassMap = new HashMap<String, GrailsDomainClass>();
    for (Object o : sessionFactory.getAllClassMetadata().values()) {
        ClassMetadata classMetadata = (ClassMetadata) o;
        configureDomainClass(sessionFactory, application, classMetadata,
                classMetadata.getMappedClass(EntityMode.POJO), hibernateDomainClassMap);
    }/* www.  j  av a 2 s  .c o  m*/
    configureInheritanceMappings(hibernateDomainClassMap);
}

From source file:org.compass.gps.device.hibernate.entities.DefaultHibernateEntitiesLocator.java

License:Apache License

public EntityInformation[] locate(SessionFactory sessionFactory, HibernateGpsDevice device)
        throws HibernateGpsDeviceException {

    CompassGpsInterfaceDevice gps = (CompassGpsInterfaceDevice) device.getGps();

    ArrayList<EntityInformation> entitiesList = new ArrayList<EntityInformation>();

    Map allClassMetaData = sessionFactory.getAllClassMetadata();
    for (Iterator it = allClassMetaData.keySet().iterator(); it.hasNext();) {
        String entityname = (String) it.next();
        if (!gps.hasMappingForEntityForIndex((entityname))) {
            if (log.isDebugEnabled()) {
                log.debug("Entity [" + entityname + "] does not have compass mapping, filtering it out");
            }/*from  w  w w.  ja va  2 s. co  m*/
            continue;
        }

        ClassMetadata classMetadata = (ClassMetadata) allClassMetaData.get(entityname);
        if (shouldFilter(entityname, classMetadata, allClassMetaData, device)) {
            continue;
        }
        Class clazz = classMetadata.getMappedClass(EntityMode.POJO);
        ResourceMapping resourceMapping = gps.getMappingForEntityForIndex(entityname);
        EntityInformation entityInformation = new EntityInformation(clazz, entityname,
                resourceMapping.getSubIndexHash().getSubIndexes());
        entitiesList.add(entityInformation);
        if (log.isDebugEnabled()) {
            log.debug("Entity [" + entityname + "] will be indexed");
        }
    }
    return entitiesList.toArray(new EntityInformation[entitiesList.size()]);
}

From source file:org.compass.gps.device.jpa.entities.HibernateJpaEntitiesLocator.java

License:Apache License

public EntityInformation[] locate(EntityManagerFactory entityManagerFactory, JpaGpsDevice device)
        throws JpaGpsDeviceException {

    CompassGpsInterfaceDevice gps = (CompassGpsInterfaceDevice) device.getGps();

    HibernateEntityManagerFactory hibernateEntityManagerFactory = (HibernateEntityManagerFactory) entityManagerFactory;
    SessionFactory sessionFactory = hibernateEntityManagerFactory.getSessionFactory();

    ArrayList<EntityInformation> entitiesList = new ArrayList<EntityInformation>();

    Map allClassMetaData = sessionFactory.getAllClassMetadata();
    for (Object o : allClassMetaData.keySet()) {
        String entityname = (String) o;
        if (!gps.hasMappingForEntityForIndex((entityname))) {
            if (log.isDebugEnabled()) {
                log.debug("Entity [" + entityname + "] does not have compass mapping, filtering it out");
            }//from w ww .  jav a2 s . c om
            continue;
        }

        ClassMetadata classMetadata = (ClassMetadata) allClassMetaData.get(entityname);
        if (shouldFilter(entityname, classMetadata, allClassMetaData, device)) {
            continue;
        }
        Class<?> clazz = classMetadata.getMappedClass(EntityMode.POJO);
        ResourceMapping resourceMapping = gps.getMappingForEntityForIndex(entityname);
        EntityInformation entityInformation = new EntityInformation(clazz, entityname,
                new HibernateJpaQueryProvider(clazz, entityname),
                resourceMapping.getSubIndexHash().getSubIndexes());
        entitiesList.add(entityInformation);
        if (log.isDebugEnabled()) {
            log.debug("Entity [" + entityname + "] will be indexed");
        }
    }
    return entitiesList.toArray(new EntityInformation[entitiesList.size()]);
}