Example usage for org.hibernate SessionFactory getClassMetadata

List of usage examples for org.hibernate SessionFactory getClassMetadata

Introduction

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

Prototype

@Deprecated
ClassMetadata getClassMetadata(String entityName);

Source Link

Document

Retrieve the ClassMetadata associated with the given entity class.

Usage

From source file:com.webbfontaine.valuewebb.action.rimm.CacheCleaner.java

License:Open Source License

public Object clean() {

    if (StringUtils.trimToNull(entityClass) != null) {

        EntityManager entityManager = Utils.getEntityManager();
        SessionFactory sf = ((Session) entityManager.getDelegate()).getSessionFactory();
        EntityPersister classMetadata = (EntityPersister) sf.getClassMetadata(entityClass);
        if (classMetadata != null && classMetadata.hasCache()) {
            LOGGER.info("Evicting cache for {0}", entityClass);
            sf.evictEntity(entityClass);
            sf.evictQueries();/*from  www .  j ava 2  s.  co  m*/
            InfoHandling.getInstance().setInfoList("Cache evicted");
        } else {
            ErrorHandling.addFacesMessageError(null, "Entity is not cached");
        }
    }
    return "";
}

From source file:cz.jirutka.rsql.hibernate.AbstractCriterionBuilderTest.java

License:Open Source License

@Test
public void testIsPropertyName() {
    SessionFactory sf = SessionFactoryInitializer.getSessionFactory();
    ClassMetadata classMetadata = sf.getClassMetadata(Course.class);

    assertTrue(instance.isPropertyName("code", classMetadata));
    assertTrue(instance.isPropertyName("department", classMetadata));
    assertFalse(instance.isPropertyName("foo", classMetadata));
}

From source file:cz.jirutka.rsql.hibernate.AbstractCriterionBuilderTest.java

License:Open Source License

@Test
public void testFindPropertyType() {
    SessionFactory sf = SessionFactoryInitializer.getSessionFactory();
    ClassMetadata classMetadata = sf.getClassMetadata(Course.class);

    assertSame(String.class, instance.findPropertyType("code", classMetadata));
    assertSame(Boolean.class, instance.findPropertyType("active", classMetadata));
    assertSame(Department.class, instance.findPropertyType("department", classMetadata));
    assertNotSame(Integer.class, instance.findPropertyType("code", classMetadata));
}

From source file:debop4k.data.orm.hibernate.HibernateEx.java

License:Apache License

/**
 *   ? ? . ( ??   .)/*  w w  w.j  a v  a2  s .c o  m*/
 *
 * @param factory     hibernate session factory
 * @param entityClass entity class
 * @return  
 */
public static String getEntityName(@NonNull SessionFactory factory, @NonNull Class<?> entityClass) {
    ClassMetadata meta = factory.getClassMetadata(entityClass);
    return meta.getEntityName();
}

From source file:edu.jhuapl.dorset.components.HibernateServiceTest.java

License:Open Source License

@Test
public void testCreationOfSessionFactory() {
    Properties props = getProperties();
    Config conf = ConfigFactory.parseProperties(props);

    hs = new HibernateService(conf);
    SessionFactory sf = hs.getSessionFactory();
    assertNotNull(sf);/*from  w  ww  . jav  a  2 s  .  c om*/
    assertFalse(sf.isClosed());

    // traverse through the session factory to get at configuration values
    SessionFactoryOptions sfo = sf.getSessionFactoryOptions();
    StandardServiceRegistry ssr = sfo.getServiceRegistry();
    ConfigurationService cs = ssr.getService(ConfigurationService.class);
    assertEquals(props.getProperty("hibernate.connection.driver_class"),
            cs.getSetting("hibernate.connection.driver_class", StandardConverters.STRING));
    assertEquals(props.getProperty("hibernate.connection.url"),
            cs.getSetting("hibernate.connection.url", StandardConverters.STRING));
    assertEquals(props.getProperty("hibernate.dialect"),
            cs.getSetting("hibernate.dialect", StandardConverters.STRING));
    assertEquals(props.getProperty("hibernate.hbm2ddl.auto"),
            cs.getSetting("hibernate.hbm2ddl.auto", StandardConverters.STRING));

    // check mapping
    ClassMetadata cm = sf.getClassMetadata(TestObject.class);
    String[] names = cm.getPropertyNames();
    assertEquals(1, names.length);
    assertEquals("name", names[0]);
    assertEquals("string", cm.getPropertyType("name").getName());
}

From source file:edu.utah.further.core.data.util.HibernateUtil.java

License:Apache License

/**
 * Generates an SQL in (...) statement to be used with in statements involving
 * composite keys./*from ww w  .j a  v a 2s  .  co  m*/
 *
 * This method is strictly a workaround utility method for an issue with using
 * {@link Restrictions#in(String, java.util.Collection)} with a composite key. It
 * generates an sql statement correctly but binds the parameters wrong. This issue has
 * been reported SEVERAL times, as early as 05 and it still hasn't been fixed (it's
 * 09). There is a 2 second correction that needs to be added to the code to fix the
 * issue but for some reason Hibernate developers refuse to do it. In light of not
 * knowing what else it might break in custom compiling Hibernate with the fix it was
 * preferred to do a work around. It is to be used directly with
 * {@link Restrictions#sqlRestriction(String)}.
 *
 * @param entityClass
 *            the entity which contains the composite key for which an SQL in
 *            statement needs to be generated
 * @param sessionFactory
 *            the {@link SessionFactory} assosciated with the entities
 * @param elementsSize
 *            the size of the elements that will be in the in clause
 * @return
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-708
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-1575
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-1743
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-1832
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-1972
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-3164
 */
public static String sqlRestrictionCompositeIn(final Class<? extends PersistentEntity<?>> entityClass,
        final SessionFactory sessionFactory, final int elementsSize) {
    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
    final String identifierName = classMetadata.getIdentifierPropertyName();
    final Type identifierType = classMetadata.getIdentifierType();

    if (!(identifierType.isComponentType())) {
        return Strings.EMPTY_STRING;
    }

    final ComponentType componentType = (ComponentType) identifierType;
    final String[] idPropertyNames = componentType.getPropertyNames();

    final PropertyMapping propertyMapping = getPropertyMapping(entityClass, sessionFactory);

    final StringBuilder inString = StringUtil.newStringBuilder();

    // field names -- ({alias}.field1, {alias}.field2)
    inString.append('(');
    for (int i = 0; i < idPropertyNames.length; i++) {
        inString.append("{alias}").append('.')
                // Look up the database field from the property path
                .append(propertyMapping.toColumns(identifierName + "." + idPropertyNames[i])[0]);
        if (i + 1 < idPropertyNames.length) {
            inString.append(", ");
        } else {
            inString.append(')');
        }
    }

    // values -- in ( (?, ?), (?, ?) )
    inString.append(" in ").append('(');
    for (int i = 0; i < elementsSize; i++) {
        if (elementsSize % MAX_IN == 0) {
            inString.append(')');
            inString.append(Strings.EMPTY_STRING);
            inString.append("or");
            inString.append(Strings.EMPTY_STRING);
            inString.append('(');
        }

        inString.append('(');
        for (int j = 0; j < idPropertyNames.length; j++) {
            inString.append('?');
            if (j + 1 < idPropertyNames.length) {
                inString.append(",");
            }
        }
        inString.append(')');
        if ((i + 1 < elementsSize) && (i + 1 % MAX_IN != 0)) {
            inString.append(", ");
        }
    }
    inString.append(')');

    return inString.toString();
}

From source file:edu.utah.further.ds.impl.executor.db.hibernate.criteria.HibernateCountSearchQueryExecutor.java

License:Apache License

@SuppressWarnings("boxing")
@Override//  ww w . j a  v a2  s .  com
public boolean process(final ChainRequest request) {
    final HibernateExecReq execReq = new HibernateExecReq(request);
    final GenericCriteria criteria = execReq.getResult();
    notNull(criteria, "Expected Hibernate criteria");

    final Class<? extends PersistentEntity<?>> domainClass = execReq.getRootEntity();

    final SessionFactory sessionFactory = execReq.getSessionFactory();
    notNull(sessionFactory, "Expected SessionFactory");

    // Get information about the root entity class
    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(domainClass);
    final String identifierName = classMetadata.getIdentifierPropertyName();
    final Type identifierType = classMetadata.getIdentifierType();

    if (identifierType.isComponentType()) {
        criteria.setProjection(Projections.countDistinct(identifierName + "." + identifierName));
    } else {
        criteria.setProjection(Projections.countDistinct(identifierName));
    }
    Long result = -1l;
    try {
        result = criteria.uniqueResult();
    } catch (final HibernateException e) {
        if (log.isDebugEnabled()) {
            log.debug("Caught Hibernate exception.");
        }
    }

    execReq.setResult(result);
    execReq.setStatus("Returned search query count result");

    return false;
}

From source file:edu.utah.further.ds.impl.executor.db.hibernate.criteria.HibernateDistinctEntityExecutor.java

License:Apache License

@Override
public boolean process(final ChainRequest request) {
    final HibernateExecReq execReq = new HibernateExecReq(request);
    final GenericCriteria criteria = execReq.getResult();
    notNull(criteria, "Expected Hibernate criteria");

    final Class<? extends PersistentEntity<?>> domainClass = execReq.getRootEntity();

    final SessionFactory sessionFactory = execReq.getSessionFactory();
    notNull(sessionFactory, "Expected SessionFactory");

    // Get information about the root entity class
    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(domainClass);
    final String[] properties = classMetadata.getPropertyNames();
    final String identifierName = classMetadata.getIdentifierPropertyName();

    final ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.distinct(Projections.property(identifierName)), identifierName);

    // When you use projections, you have to manually specify the selection criteria
    // so we loop through all the properties and specify them here. Note that we skip
    // all the relationship properties (collections).
    for (final String property : properties) {
        final Type type = classMetadata.getPropertyType(property);
        if (!type.isCollectionType()) {
            projectionList.add(Projections.property(property), property);
        }/* ww w. j  av a  2 s  .  co m*/
    }

    criteria.setProjection(projectionList);

    // This turns all of the results into the actual root entity class - calling
    // setters/etc
    criteria.setResultTransformer(new AliasToBeanResultTransformer(domainClass));

    execReq.setResult(criteria);

    return false;
}

From source file:edu.utah.further.ds.impl.executor.db.hibernate.criteria.HibernateDistinctIdExecutor.java

License:Apache License

/**
 * @param request/*from  ww w.  j a  v  a 2  s.c  o m*/
 * @return
 * @see edu.utah.further.core.chain.AbstractRequestHandler#process(edu.utah.further.core.api.chain.ChainRequest)
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
 */
@Override
public boolean process(final ChainRequest request) {
    final HibernateExecReq executionReq = new HibernateExecReq(request);

    // Validate required input
    final GenericCriteria hibernateCriteria = executionReq.getResult();
    notNull(hibernateCriteria, "Expected Hibernate criteria");

    final Class<? extends PersistentEntity<?>> domainClass = executionReq.getRootEntity();
    final Class<? extends PersistentEntity<?>> entityClass = dao.getEntityClass(domainClass);

    notNull(entityClass, "Expected root entity class");

    final SessionFactory sessionFactory = executionReq.getSessionFactory();
    notNull(sessionFactory, "Expected SessionFactory");

    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
    final String identifierName = classMetadata.getIdentifierPropertyName();
    final Type identifierType = classMetadata.getIdentifierType();

    // A hack to obtain projections out of the critieria by casting to the Hibernate
    // implementation. TODO: improve adapter to do that via interface access
    final ProjectionList projectionList = Projections.projectionList();
    final Projection existingProjection = ((CriteriaImpl) hibernateCriteria.getHibernateCriteria())
            .getProjection();

    if (existingProjection != null && !overrideExistingProjection) {
        return false;
    }

    if (identifierType.isComponentType()) {
        final ComponentType componentType = (ComponentType) identifierType;
        final String[] idPropertyNames = componentType.getPropertyNames();

        // Add distinct to the first property
        projectionList.add(
                Projections
                        .distinct(Property.forName(identifierName + PROPERTY_SCOPE_CHAR + idPropertyNames[0])),
                idPropertyNames[0]);

        // Add the remaining properties to the projection list
        for (int i = 1; i < idPropertyNames.length; i++) {
            projectionList.add(Property.forName(identifierName + PROPERTY_SCOPE_CHAR + idPropertyNames[i]),
                    idPropertyNames[i]);
        }

        hibernateCriteria.setProjection(projectionList);
        hibernateCriteria.setResultTransformer(new AliasToBeanResultTransformer(
                ReflectionUtils.findField(entityClass, identifierName).getType()));
    } else {
        // 'this' required to avoid HHH-817
        projectionList.add(Projections.distinct(Property.forName(THIS_CONTEXT + identifierName)));
        hibernateCriteria.setProjection(projectionList);
    }

    executionReq.setResult(hibernateCriteria);

    return false;
}

From source file:edu.utah.further.ds.impl.executor.db.hibernate.criteria.HibernateLoadByIdExecutor.java

License:Apache License

/**
 * @param request//from w  w w .  ja  v  a2s  .  c o  m
 * @return
 * @see edu.utah.further.core.chain.AbstractRequestHandler#process(edu.utah.further.core.api.chain.ChainRequest)
 */
@Override
public boolean process(final ChainRequest request) {
    // Read input arguments
    final HibernateExecReq executionReq = new HibernateExecReq(request);
    final SessionFactory sessionFactory = executionReq.getSessionFactory();
    notNull(sessionFactory, "Expected SessionFactory");

    final Class<? extends PersistentEntity<?>> rootEntity = executionReq.getRootEntity();
    notNull(rootEntity, "Expected root entity class");

    // Read the search criteria's root entity meta data
    final List<Object> list = executionReq.getResult();
    final Object[] listArray = CollectionUtil.toArrayNullSafe(list);
    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(rootEntity);
    final String identifierName = classMetadata.getIdentifierPropertyName();
    final Type identifierType = classMetadata.getIdentifierType();
    final int numTypes = listArray.length;
    final Type[] types = new Type[numTypes];
    for (int i = 0; i < numTypes; i++) {
        types[i] = identifierType;
    }

    // Build Hibernate criteria
    final GenericCriteria criteria = GenericCriteriaFactory.criteria(CriteriaType.CRITERIA, rootEntity,
            sessionFactory.getCurrentSession());
    if (identifierType.isComponentType()) {
        final String sqlInClause = HibernateUtil.sqlRestrictionCompositeIn(rootEntity, sessionFactory,
                numTypes);
        criteria.add(Restrictions.sqlRestriction(sqlInClause, listArray, types));
    } else {
        final int size = list.size();
        if (size > MAX_IN) {
            // Create a disjunction of IN clauses. Add MAX_IN elements at a time to
            // each IN clause (except the last IN, whose size is size % MAX_IN).
            final Junction junction = Restrictions.disjunction();
            for (int i = 0; i < size; i += MAX_IN) {
                junction.add(
                        Restrictions.in(THIS + identifierName, list.subList(i, Math.max(size, MAX_IN + i))));
            }
            criteria.add(junction);
        } else {
            // Single chunk, add directly as a criterion without the junction trick
            criteria.add(Restrictions.in(THIS + identifierName, list));
        }

    }

    executionReq.setResult(criteria);
    return false;
}