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:org.nextframework.persistence.PersistenceUtils.java

License:Apache License

public static Class<?> getPropertyAssociationType(SessionFactory sessionFactory, Class<?> clazz,
        String property) {/*from w  w  w . j  a  v  a2 s  .  c om*/
    Class<?> result = null;
    ClassMetadata classMetadata = getClassMetadata(clazz, sessionFactory);
    if (classMetadata == null) {
        throw new PersistenceException("Class " + clazz.getName() + " is not mapped. ");
    }
    org.hibernate.type.Type propertyType = classMetadata.getPropertyType(property);
    if (propertyType instanceof AssociationType) {
        AssociationType associationType = (AssociationType) propertyType;
        String associatedEntityName = associationType
                .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
        AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) sessionFactory
                .getClassMetadata(associatedEntityName);
        result = abstractEntityPersister.getEntityType().getReturnedClass();
    } else {
        throw new PersistenceException("Property \"" + property + "\" of " + clazz
                + " is not an association type (i.e. ManyToOne, OneToMany, AnyType, etc)");
    }
    return result;
}

From source file:org.openeos.services.dictionary.internal.HibernateAnnotationsMixedClassDefinitionImpl.java

License:Apache License

public HibernateAnnotationsMixedClassDefinitionImpl(EntityToStringService entityToStringService,
        SessionFactory sessionFactory, Class<?> classDefined) {
    this.entityToStringService = entityToStringService;
    this.sessionFactory = sessionFactory;
    this.classDefined = classDefined;
    this.classMetadata = sessionFactory.getClassMetadata(classDefined);
}

From source file:org.openmrs.module.dictionarypublishing.api.db.hibernate.HibernateDictionaryPublishingDAO.java

License:Open Source License

/**
 * @param sessionFactory the sessionFactory to set
 *//*from  w w  w .  j  ava 2s  . co  m*/
public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;

    hasDateRetiredColumn = ArrayUtils
            .contains(sessionFactory.getClassMetadata(Concept.class).getPropertyNames(), "dateRetired");
}

From source file:org.openswing.swing.util.server.HibernateUtils.java

License:Open Source License

private static void fillInMetaData2( //bc
        SessionFactory sessions, String tableName, String prefix, ClassMetadata meta, Map attributesMap,
        Map attributesTypeMap, String lastAttrName, HashMap entitiesAlreadyAnalyzed, String[] attrNames) {
    if (meta != null) {
        Integer num = (Integer) entitiesAlreadyAnalyzed.get(meta.getEntityName());
        if (num == null) {
            num = new Integer(1);
            entitiesAlreadyAnalyzed.put(meta.getEntityName(), num);
        } else {/* w  w w .j ava2s  .  c o m*/
            entitiesAlreadyAnalyzed.put(meta.getEntityName(), new Integer(num.intValue() + 1));
        }
        if (num.intValue() > 50) // the same entity cannot be analyzed again more than 10 times.
        {
            return;
        }
        if (attrNames == null) {
            attrNames = meta.getPropertyNames();
        }
        for (int i = 0; i < attrNames.length; i++) {
            attributesMap.put(prefix + attrNames[i], tableName + "." + attrNames[i]);
            attributesTypeMap.put(prefix + attrNames[i], meta.getPropertyType(attrNames[i]));
            /*
            if (meta.getPropertyType(attrNames[i]) instanceof org.hibernate.type.EntityType &&
            !prefix.equals(attrNames[i]+".")) {
            ClassMetadata submeta = sessions.getClassMetadata(((org.hibernate.type.EntityType)meta.getPropertyType(attrNames[i])).getReturnedClass());
            fillInMetaData(
            sessions,
            tableName+"."+attrNames[i],
            prefix+prefix+attrNames[i]+".",
            submeta,
            attributesMap,
            attributesTypeMap
            );
            }
             */
            if (meta.getPropertyType(attrNames[i]) instanceof org.hibernate.type.EntityType
                    && !lastAttrName.equals(meta.getEntityName() + "." + attrNames[i])) {
                ClassMetadata submeta = sessions
                        .getClassMetadata(((org.hibernate.type.EntityType) meta.getPropertyType(attrNames[i]))
                                .getReturnedClass());
                fillInMetaData(sessions, tableName + "." + attrNames[i],
                        //          prefix+prefix+attrNames[i]+".",
                        // -MC 29/11/2008:
                        prefix + attrNames[i] + ".", submeta, attributesMap, attributesTypeMap,
                        meta.getEntityName() + "." + attrNames[i], entitiesAlreadyAnalyzed);
            }
            if (meta.getPropertyType(attrNames[i]) instanceof ComponentType) { //bc
                ComponentType e = ((ComponentType) meta.getPropertyType(attrNames[i]));
                String propertyNames[] = new String[e.getPropertyNames().length];
                for (int j = 0; j < e.getPropertyNames().length; j++) {
                    propertyNames[j] = attrNames[i] + "." + e.getPropertyNames()[j];
                }
                fillInMetaData2(sessions, tableName, prefix, meta, attributesMap, attributesTypeMap,
                        lastAttrName, entitiesAlreadyAnalyzed, propertyNames);
                //                    for (String name : e.getPropertyNames()) {
                //                        String attrName = attrNames[i] + "." + name;
                //                        System.out.println(attrName);
                //                        attributesMap.put(prefix + attrName, tableName + "." + attrName);
                //                        attributesTypeMap.put(prefix + attrName, meta.getPropertyType(attrName));
                //                    }
            }
            /*
            if (meta.getPropertyType(attrNames[i]) instanceof org.hibernate.type.EntityType) {
            if (!prefix.equals(attrNames[i]+".")) {
            ClassMetadata submeta =
            sessions.getClassMetadata(((org.hibernate.type.EntityType)meta.getPropertyType(attrNames[i])).getReturnedClass());
            fillInMetaData(
            sessions,
            tableName+"."+attrNames[i],
            prefix+prefix+attrNames[i]+".",
            submeta,
            attributesMap
            );
            }
            }
             */

        }

        attributesMap.put(prefix + meta.getIdentifierPropertyName(),
                tableName + "." + meta.getIdentifierPropertyName());
        attributesTypeMap.put(prefix + meta.getIdentifierPropertyName(),
                meta.getPropertyType(meta.getIdentifierPropertyName()));
        /*
        if (meta.getPropertyType(meta.getIdentifierPropertyName()) instanceof org.hibernate.type.EntityType &&
        !prefix.equals(meta.getIdentifierPropertyName()+".")) {
        ClassMetadata submeta = sessions.getClassMetadata(((org.hibernate.type.EntityType)meta.getPropertyType(meta.getIdentifierPropertyName())).getReturnedClass());
        fillInMetaData(
        sessions,
        ((org.hibernate.type.EntityType)meta.getPropertyType(meta.getIdentifierPropertyName())).getReturnedClass().getName(),
        prefix+prefix+meta.getIdentifierPropertyName()+".",
        submeta,
        attributesMap,
        attributesTypeMap
        );
        }
         */
        if (meta.getPropertyType(meta.getIdentifierPropertyName()) instanceof org.hibernate.type.EntityType
                && !lastAttrName.equals(meta.getEntityName() + "." + meta.getIdentifierPropertyName())) {
            ClassMetadata submeta = sessions.getClassMetadata(
                    ((org.hibernate.type.EntityType) meta.getPropertyType(meta.getIdentifierPropertyName()))
                            .getReturnedClass());
            fillInMetaData(sessions,
                    ((org.hibernate.type.EntityType) meta.getPropertyType(meta.getIdentifierPropertyName()))
                            .getReturnedClass().getName(),
                    prefix + prefix + meta.getIdentifierPropertyName() + ".", submeta, attributesMap,
                    attributesTypeMap, meta.getEntityName() + "." + meta.getIdentifierPropertyName(),
                    new HashMap());
        }

    }
}

From source file:org.openswing.swing.util.server.HibernateUtils.java

License:Open Source License

/**
 * Apply filtering and sorting conditions to the specified baseSQL and return
 * a new baseSQL that contains those conditions too.
 * @param decodedAttributes collection of pairs <value object attribute name,attribute defined in HSQL query>; if not specified, this method tries to automatically fetch mappings
 * @param filteredColumns filtering conditions
 * @param currentSortedColumns sorting conditions (attribute names)
 * @param currentSortedVersusColumns sorting conditions (order versus)
 * @param valueObjectType value object type
 * @param baseSQL base SQL//  w ww  .j  av  a2  s  .c om
 * @param paramValues parameters values, related to "?" in "baseSQL"
 * @param paramTypes parameters types, related to "?" in "baseSQL"
 * @param tableName table name related to baseSQL and v.o.
 * @param sessions SessionFactory
 */
public static String applyFiltersAndSorter(Map decodedAttributes, Map filteredColumns,
        ArrayList currentSortedColumns, ArrayList currentSortedVersusColumns, Class valueObjectType,
        String baseSQL, ArrayList paramValues, ArrayList paramTypes, String tableName, SessionFactory sessions)
        throws Exception {

    //    Iterator it = filteredColumns.keySet().iterator();
    //    String gridAttr,hsqlAttr;
    //    HashSet toRemove = new HashSet();
    //    HashMap toAdd = new HashMap();
    //    while(it.hasNext()) {
    //      gridAttr = it.next().toString();
    //      hsqlAttr = (String)decodedAttributes.get(gridAttr);
    //      if (hsqlAttr!=null) {
    //        toAdd.put(hsqlAttr,filteredColumns.get(gridAttr));
    //        toRemove.add(gridAttr);
    //      }
    //    }
    //    filteredColumns.putAll(toAdd);
    //    it = toRemove.iterator();
    //    while(it.hasNext())
    //      filteredColumns.remove(it.next());
    //
    //    for(int i=0;i<currentSortedColumns.size();i++) {
    //      gridAttr = currentSortedColumns.get(i).toString();
    //      hsqlAttr = (String)decodedAttributes.get(gridAttr);
    //      if (hsqlAttr!=null) {
    //        currentSortedColumns.set(i,hsqlAttr);
    //      }
    //    }

    // fill in "attributesMap" according to attributes defined in xxx.hdm.xml...
    ClassMetadata meta = sessions.getClassMetadata(valueObjectType);
    Map propDescriptors = new HashMap();
    Map attributesMap = new HashMap();
    Map attributesTypeMap = new HashMap();
    if (meta != null) {
        fillInMetaData(sessions, tableName, "", meta, attributesMap, attributesTypeMap, "", new HashMap());
        attributesMap.put(meta.getIdentifierPropertyName(), tableName + "." + meta.getIdentifierPropertyName());
    } else {
        PropertyDescriptor[] p = Introspector.getBeanInfo(valueObjectType).getPropertyDescriptors();
        for (int i = 0; i < p.length; i++) {
            propDescriptors.put(p[i].getName(), p[i].getPropertyType());
        }
    }
    attributesMap.putAll(decodedAttributes);

    // append filtering and sorting conditions to the base SQL...
    ArrayList filterAttrNames = new ArrayList();
    baseSQL = QueryUtil.getSql(new UserSessionParameters(), baseSQL, filterAttrNames, paramValues,
            filteredColumns, currentSortedColumns, currentSortedVersusColumns, attributesMap);

    FilterWhereClause[] where = null;
    for (int i = 0; i < filterAttrNames.size(); i++) {
        where = (FilterWhereClause[]) filteredColumns.get(filterAttrNames.get(i));

        if (where[0].getValue() != null && where[0].getValue() instanceof List) {
            for (int j = 0; j < ((List) where[0].getValue()).size(); j++) {
                paramTypes.add(getPropertyType(attributesTypeMap, meta, filterAttrNames.get(i).toString(),
                        propDescriptors));
            }
        } else {
            if (!where[0].getOperator().equals(Consts.IS_NOT_NULL)
                    && !where[0].getOperator().equals(Consts.IS_NULL)) { //bc
                paramTypes.add(getPropertyType(attributesTypeMap, meta, filterAttrNames.get(i).toString(),
                        propDescriptors));
            }
        }

        //      if (where[1]!=null) {
        //        if (where[1].getValue()!=null && where[1].getValue() instanceof List) {
        //          for(int j=0;j<((List)where[1].getValue()).size();j++)
        //            paramTypes.add(getPropertyType(attributesTypeMap,meta,filterAttrNames.get(i).toString(),propDescriptors));
        //        }
        //        else
        //          paramTypes.add(getPropertyType(attributesTypeMap,meta,filterAttrNames.get(i).toString(),propDescriptors));
        //      }
    }

    return baseSQL;
}

From source file:org.openswing.swing.util.server.HibernateUtils.java

License:Open Source License

/**
 * Apply filtering and sorting conditions to the specified baseSQL and return
 * a new baseSQL that contains those conditions too.
 * SQL is expressed using more argument, each one without the related keyword (select, from, ...).
 *
 * Example: following query//from  w  w w  .jav  a 2  s  .  c o m
 *
 * select customer_code,corporate_name from companiesVO order by customer_code asc
 *
 * become an invokation of getSql:
 *
 * getSql(userSessionPars,"customer_code,corporate_name","companiesVO","","customer_code asc","","",...);
 *
 * If decodedAttributes is filled, then baseSQL can contains a HSQL query.
 * @param decodedAttributes collection of pairs <value object attribute name,attribute defined in HSQL query>
 * @param filteredColumns filtering conditions
 * @param currentSortedColumns sorting conditions (attribute names)
 * @param currentSortedVersusColumns sorting conditions (order versus)
 * @param valueObjectType value object type
 * @param select list of fields for select statement
 * @param from list of tables for from statement
 * @param where where statement; may be null
 * @param group group by statement; may be null
 * @param having having statement; may be null
 * @param order list of fields for order by statement; may be null
 * @param paramValues parameters values, related to "?" in "baseSQL"
 * @param paramTypes parameters types, related to "?" in "baseSQL"
 * @param tableName table name related to baseSQL and v.o.
 * @param sessions SessionFactory
 */
public static String applyFiltersAndSorter(Map decodedAttributes, Map filteredColumns,
        ArrayList currentSortedColumns, ArrayList currentSortedVersusColumns, Class valueObjectType,
        String select, String from, String where, String group, String having, String order,
        ArrayList paramValues, ArrayList paramTypes, String tableName, SessionFactory sessions)
        throws Exception {

    //    Iterator it = filteredColumns.keySet().iterator();
    //    String gridAttr,hsqlAttr;
    //    HashSet toRemove = new HashSet();
    //    HashMap toAdd = new HashMap();
    //    while(it.hasNext()) {
    //      gridAttr = it.next().toString();
    //      hsqlAttr = (String)decodedAttributes.get(gridAttr);
    //      if (hsqlAttr!=null) {
    //        toAdd.put(hsqlAttr,filteredColumns.get(gridAttr));
    //        toRemove.add(gridAttr);
    //      }
    //    }
    //    filteredColumns.putAll(toAdd);
    //    it = toRemove.iterator();
    //    while(it.hasNext())
    //      filteredColumns.remove(it.next());
    //
    //    for(int i=0;i<currentSortedColumns.size();i++) {
    //      gridAttr = currentSortedColumns.get(i).toString();
    //      hsqlAttr = (String)decodedAttributes.get(gridAttr);
    //      if (hsqlAttr!=null) {
    //        currentSortedColumns.set(i,hsqlAttr);
    //      }
    //    }

    // fill in "attributesMap" according to attributes defined in xxx.hdm.xml...
    ClassMetadata meta = sessions.getClassMetadata(valueObjectType);
    Map attributesMap = new HashMap();
    Map attributesTypeMap = new HashMap();
    Map propDescriptors = new HashMap();
    if (meta != null) {
        fillInMetaData(sessions, tableName, "", meta, attributesMap, attributesTypeMap, "", new HashMap());
        attributesMap.put(meta.getIdentifierPropertyName(), tableName + "." + meta.getIdentifierPropertyName());
    } else {
        PropertyDescriptor[] p = Introspector.getBeanInfo(valueObjectType).getPropertyDescriptors();
        for (int i = 0; i < p.length; i++) {
            propDescriptors.put(p[i].getName(), p[i].getPropertyType());
        }
    }
    attributesMap.putAll(decodedAttributes);

    // append filtering and sorting conditions to the base SQL...
    ArrayList filterAttrNames = new ArrayList();
    String baseSQL = QueryUtil.getSql(new UserSessionParameters(), select, from, where, group, having, order,
            filterAttrNames, paramValues, filteredColumns, currentSortedColumns, currentSortedVersusColumns,
            attributesMap);

    FilterWhereClause[] whereC = null;
    for (int i = 0; i < filterAttrNames.size(); i++) {
        whereC = (FilterWhereClause[]) filteredColumns.get(filterAttrNames.get(i));

        if (whereC[0].getValue() != null && whereC[0].getValue() instanceof List) {
            for (int j = 0; j < ((List) whereC[0].getValue()).size(); j++) {
                paramTypes.add(getPropertyType(attributesTypeMap, meta, filterAttrNames.get(i).toString(),
                        propDescriptors));
            }
        } else {
            paramTypes.add(getPropertyType(attributesTypeMap, meta, filterAttrNames.get(i).toString(),
                    propDescriptors));
        }

        //      if (whereC[1]!=null) {
        //        if (whereC[1].getValue()!=null && whereC[1].getValue() instanceof List) {
        //          for(int j=0;j<((List)whereC[1].getValue()).size();j++)
        //            paramTypes.add(getPropertyType(attributesTypeMap,meta,filterAttrNames.get(i).toString(),propDescriptors));
        //        }
        //        else
        //          paramTypes.add(getPropertyType(attributesTypeMap,meta,filterAttrNames.get(i).toString(),propDescriptors));
        //      }
    }

    return baseSQL;
}

From source file:org.opentaps.foundation.infrastructure.Infrastructure.java

License:Open Source License

/**
 * Evict an entry from the second-level cache.
 * @param sessionFactory a <code>SessionFactory</code> instance
 * @param persistentClass a <code>Class</code> instance
 * @param id a <code>Serializable</code> instance
 *///w ww  .  j  av a  2  s  . c  o  m
public void evictHibernateCache(SessionFactory sessionFactory, Class<?> persistentClass, Serializable id) {
    if (sessionFactory != null) {
        ClassMetadata classMetadata = sessionFactory.getClassMetadata(persistentClass);
        // ensure the persistentClass is an entity class
        if (classMetadata != null) {
            if (id == null) {
                sessionFactory.evict(persistentClass);
            } else {
                sessionFactory.evict(persistentClass, id);
            }
        }
    }
}

From source file:org.ow2.bonita.type.matcher.HibernateIdMatcher.java

License:Open Source License

public boolean matches(String name, Object value) {
    boolean matches = false;

    Environment environment = Environment.getCurrent();
    if (environment != null) {
        SessionFactory sessionFactory = null;
        if (hibernateSessionFactoryName != null) {
            sessionFactory = (SessionFactory) environment.get(hibernateSessionFactoryName);
        } else {/* ww w.java  2s.  com*/
            sessionFactory = environment.get(SessionFactory.class);
        }
        if (sessionFactory != null) {
            ClassMetadata classMetadata = sessionFactory.getClassMetadata(value.getClass());
            matches = ((classMetadata != null)
                    && (classMetadata.getIdentifierType().getClass() == getIdType()));
        }
    } else {
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine(
                    "no current environment so valueClass cannot be stored as an id-ref to a hibernate object");
        }
        matches = false;
    }
    return matches;
}

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

License:Apache License

/**
 * Returns the identifier of the given ActiveRecord. The id is obtained
 * using the Hibernate meta-data API./*from  w  w  w  .  j a va 2s  . c  o  m*/
 * 
 * @see ClassMetadata#getIdentifier(Object, EntityMode)
 */
public static Serializable getId(ActiveRecord record) {
    SessionFactory sessionFactory = ActiveRecord.getSessionFactory();
    if (sessionFactory == null) {
        return "N/A";
    }
    return sessionFactory.getClassMetadata(getClass(record)).getIdentifier(record, EntityMode.POJO);
}

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

License:Apache License

@SuppressWarnings("unchecked")
public static Class<? extends Serializable> getIdentifierClass(Class<?> beanClass,
        SessionFactory sessionFactory) {

    return sessionFactory.getClassMetadata(beanClass).getIdentifierType().getReturnedClass();
}