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:at.molindo.esi4j.module.hibernate.HibernateEntityResolver.java

License:Apache License

/**
 * must be called within originating session
 *//*from   w  w  w  . j  a  v  a 2  s  . c o  m*/
@Override
public ObjectKey toObjectKey(Object entity) {
    SessionFactory factory = getSessionFactory();

    Session session = getCurrentSession(factory);

    String entityName = _entityNames.find(entity.getClass());

    ClassMetadata meta = factory.getClassMetadata(entityName);

    Class<?> type = meta.getMappedClass();

    Serializable id = meta.getIdentifier(entity, (SessionImpl) session);
    Long version = toLongVersion(meta.getVersion(entity));

    return new ObjectKey(type, id, version);
}

From source file:br.com.arsmachina.dao.hibernate.BaseHibernateDAO.java

License:Apache License

/**
 * Constructor that takes a {@link Class} and a {@link SessionFactory}.
 * //from   w w w  . jav  a  2 s . co  m
 * @param clasz a {@link Class}.
 * @param sessionFactory a {@link SessionFactory}. It cannot be null.
 */
@SuppressWarnings("unchecked")
public BaseHibernateDAO(Class<T> clasz, SessionFactory sessionFactory) {

    if (sessionFactory == null) {
        throw new IllegalArgumentException("Parameter sessionFactory cannot be null");
    }

    this.sessionFactory = sessionFactory;

    entityClass = clasz != null ? clasz : extractEntityClassFromHierarchy();
    classMetadata = sessionFactory.getClassMetadata(getEntityClass());

    if (getClassMetadata() == null) {
        throw new RuntimeException("Class " + getEntityClass().getName() + " is not mapped");
    }

    primaryKeyPropertyName = getClassMetadata().getIdentifierPropertyName();

    assert getEntityClass() != null;
    assert getClassMetadata() != null;
    assert getPrimaryKeyPropertyName() != null;

}

From source file:com.autobizlogic.abl.engine.phase.AdjustAllParents.java

License:Open Source License

/**
 * For each parent object, see if any adjustment is required (sums, count, ...)
 * @see  #execute(LogicRunner)/* w  w  w. j  a va2s . c  om*/
 */
@Override
public void execute() {
    if (_logSys.isDebugEnabled())
        _logSys.debug("#checking parent adjustments for", childLogicRunner);
    List<MetaRole> rtnRolesProcessed = new ArrayList<MetaRole>();

    BusinessLogicFactory businessLogicFactory = BusinessLogicFactoryManager.getBusinessLogicFactory();

    if (childDomainObject != null) {
        Set<MetaRole> childrenRoles = childDomainObject.getMetaEntity().getRolesFromChildToParents();
        for (MetaRole eachChildrenRoles : childrenRoles) {
            MetaRole roleToChild = eachChildrenRoles.getOtherMetaRole();
            if (roleToChild == null) // Is this a one-way relationship? If so, nothing to do in the parent
                continue;
            rtnRolesProcessed.add(roleToChild);

            MetaEntity parentEntity = roleToChild.getMetaEntity();

            Object parentObject = getChildLogicRunner().getCurrentDomainObject()
                    .get(eachChildrenRoles.getRoleName());

            // Make sure that the parent and the child point to each other
            // In the case of a delete, Hibernate will often remove the child object from
            // the parent collection by the time we get here, so we can't really check.
            if (parentObject != null && !childDomainObject.isMap()
                    && childLogicRunner.getVerb() != Verb.DELETE) {
                Object children = ObjectUtil.getProperty(parentObject, roleToChild.getName());
                boolean badRelationship = false;
                if (children == null)
                    badRelationship = true;
                else if (children instanceof Collection) {
                    Collection<?> theChildren = (Collection<?>) children;
                    if (!theChildren.contains(childDomainObject.getEntity())) {
                        theChildren.contains(childDomainObject.getEntity());
                        for (Object o : theChildren) {
                            System.out.println("Object " + o + " == " + childDomainObject.getEntity() + " : "
                                    + o.equals(childDomainObject.getEntity()));
                        }
                        badRelationship = true;
                    }
                }
                if (badRelationship)
                    HibernateUtil.failInconsistentRelationship(parentObject, childDomainObject, roleToChild);
            }

            // In case there is some inheritance situation, get the actual parent object and
            // see what class it is.
            if (parentObject != null && !parentObject.getClass().equals(parentEntity.getEntityClass())
                    && !parentEntity.isMap()) {
                Class<?> parentCls = ProxyUtil.getNonProxyClass(parentObject);
                ClassMetadata parentMeta = getChildLogicRunner().getContext().getSession().getSessionFactory()
                        .getClassMetadata(parentCls);
                String parentEntityName = parentMeta.getEntityName();
                parentEntity = parentEntity.getMetaModel().getMetaEntity(parentEntityName);
            }
            LogicGroup parentLg = RuleManager.getInstance(parentEntity.getMetaModel())
                    .getLogicGroupForEntity(parentEntity);
            if (parentLg == null && parentEntity.isMap())
                continue;
            if (parentObject != null && parentLg == null) {
                SessionFactory sessFact = getChildLogicRunner().getContext().getSession().getSessionFactory();
                Class<?> parentCls = ProxyUtil.getNonProxyClass(parentObject);
                while (parentLg == null) {
                    parentCls = parentCls.getSuperclass();
                    if (parentCls.getName().equals("java.lang.Object"))
                        break;
                    ClassMetadata classMeta = sessFact.getClassMetadata(parentCls);
                    if (classMeta == null)
                        break;
                    String parentEntityName = classMeta.getEntityName();
                    parentEntity = parentEntity.getMetaModel().getMetaEntity(parentEntityName);
                    parentLg = RuleManager.getInstance(parentEntity.getMetaModel())
                            .getLogicGroupForEntity(parentEntity);
                }
            }
            if (parentLg == null)
                continue;
            Set<AbstractAggregateRule> aggregates = parentLg.findAggregatesForRole(roleToChild);
            adjustedParentDomainObject = null; // set in eachAggregate.adjustedParentDomainObject if appropriate
            adjustedOldParentDomainObject = null;
            adjustedPriorParentDomainObject = null;
            adjustedPriorOldParentDomainObject = null;
            for (AbstractAggregateRule eachAggregate : aggregates) {
                eachAggregate.adjustedParentDomainObject(this); // do adjusts into parent (on 1st, read and return parent handle)
            }
            if (adjustedParentDomainObject != null) { // save parent, which runs its rules (fwd chain)
                if (_logger.isDebugEnabled())
                    _logger.debug("Adjusting parent " + adjustedParentDomainObject.toShortString() + " from",
                            childLogicRunner);
                LogicRunner parentLogicRunner = businessLogicFactory.getLogicRunner(
                        childLogicRunner.getContext(), adjustedParentDomainObject,
                        adjustedOldParentDomainObject, Verb.UPDATE, LogicSource.ADJUSTED, childLogicRunner,
                        roleToChild);
                if (parentLogicRunner != null)
                    parentLogicRunner.update();
            }

            if (adjustedPriorParentDomainObject != null) { // save PRIOR parent, which runs its rules (fwd chain) FIXME REPARENT
                if (_logger.isDebugEnabled())
                    _logger.debug("Adjusting PRIOR Parent " + adjustedPriorParentDomainObject.toShortString()
                            + " from", childLogicRunner);
                LogicRunner oldParentLogicRunner = businessLogicFactory.getLogicRunner(
                        childLogicRunner.getContext(), adjustedPriorParentDomainObject,
                        adjustedPriorOldParentDomainObject, Verb.UPDATE, LogicSource.ADJUSTED, childLogicRunner,
                        roleToChild);
                if (oldParentLogicRunner != null)
                    oldParentLogicRunner.update(); // See above
            } // adjustedOldParentDomeainObject != null
        } // eachChildrenRoles
    } // childDomainObject != null

    childLogicRunner.setAdjustedRolesDB(rtnRolesProcessed);
}

From source file:com.autobizlogic.abl.hibernate.HibernateUtil.java

License:Open Source License

/**
 * Given two persistent beans, which may or may not be proxies, determine whether they refer
 * to the same persistent object. In other words, are they of the same class, and do they
 * have the same primary key?//from ww w .  j av  a  2  s .co m
 * If both beans are null, this will return true.
 */
public static boolean beansHaveSamePK(Object bean1, Object bean2, Session session) {

    if (bean1 == null && bean2 == null)
        return true;

    if (bean1 == null && bean2 != null)
        return false;

    if (bean1 != null && bean2 == null)
        return false;

    if (bean1 == bean2)
        return true;

    String bean1ClassName = getEntityNameForObject(bean1);
    String bean2ClassName = getEntityNameForObject(bean2);
    if (!bean1ClassName.equals(bean2ClassName))
        return false;

    SessionFactory sf = session.getSessionFactory();
    ClassMetadata meta = sf.getClassMetadata(bean1ClassName);
    if (meta == null)
        throw new RuntimeException("Unable to get Hibernate metadata for: " + bean1ClassName);
    Object pk1 = meta.getIdentifier(bean1, (SessionImplementor) session);
    Object pk2 = meta.getIdentifier(bean2, (SessionImplementor) session);
    if (pk1 == null || pk2 == null)
        return false;
    return pk1.equals(pk2);
}

From source file:com.autobizlogic.abl.metadata.hibernate.HibMetaRole.java

License:Open Source License

/**
 * Get the opposite role of the given role, if it exists
 * @param entityName The name of the entity who owns the role, e.g. com.foo.Customer
 * @param rName The role name, e.g. orders
 * @return Null if the role has no known inverse, or [entity name, role name] of the inverse
 *//*from   w  ww  . j  ava  2 s .  c om*/
private String[] getInverseOfRole(String entityName, String rName) {

    SessionFactory sessFact = ((HibMetaModel) getMetaEntity().getMetaModel()).getSessionFactory();
    ClassMetadata classMeta = sessFact.getClassMetadata(entityName);
    Type propType = classMeta.getPropertyType(rName);
    if (propType.isCollectionType()) {
        return getInverseOfCollectionRole(entityName, rName);
    }

    if (propType.isEntityType()) {
        return getInverseOfSingleRole(entityName, rName);
    }

    log.debug("Role " + entityName + "." + rName + " is neither a collection type "
            + "nor an entity type, and will be assumed to have no inverse.");
    return null;
}

From source file:com.autobizlogic.abl.metadata.hibernate.HibMetaRole.java

License:Open Source License

/**
 * Get the inverse of a one-to-many role
 * @param entityName The entity owning the role
 * @param rName The role name/*from   w  ww . j a v a  2 s  . c o  m*/
 * @return Null if no inverse was found, otherwise [entity name, role name] of the inverse role
 */
private String[] getInverseOfCollectionRole(String entityName, String rName) {
    String[] result = new String[2];

    SessionFactory sessFact = ((HibMetaModel) getMetaEntity().getMetaModel()).getSessionFactory();
    AbstractCollectionPersister parentMeta = (AbstractCollectionPersister) sessFact
            .getCollectionMetadata(entityName + "." + rName);
    if (parentMeta == null) { // Could be inherited -- search through superclasses
        while (parentMeta == null) {
            Class<?> cls = null;
            if (getMetaEntity().getEntityType() == MetaEntity.EntityType.POJO)
                cls = sessFact.getClassMetadata(entityName).getMappedClass(EntityMode.POJO);
            else
                cls = sessFact.getClassMetadata(entityName).getMappedClass(EntityMode.MAP);
            Class<?> superCls = cls.getSuperclass();
            if (superCls.getName().equals("java.lang.Object"))
                throw new RuntimeException(
                        "Unable to retrieve Hibernate information for collection " + entityName + "." + rName);
            ClassMetadata clsMeta = sessFact.getClassMetadata(superCls);
            if (clsMeta == null)
                throw new RuntimeException("Unable to retrieve Hibernate information for collection "
                        + entityName + "." + rName + ", even from superclass(es)");
            entityName = clsMeta.getEntityName();
            parentMeta = (AbstractCollectionPersister) sessFact.getCollectionMetadata(entityName + "." + rName);
        }
    }
    String[] colNames = parentMeta.getKeyColumnNames();
    String childName = parentMeta.getElementType().getName();

    AbstractEntityPersister childMeta = (AbstractEntityPersister) sessFact.getClassMetadata(childName);
    String[] propNames = childMeta.getPropertyNames();
    for (int i = 0; i < propNames.length; i++) {
        Type type = childMeta.getPropertyType(propNames[i]);
        if (!type.isEntityType())
            continue;
        EntityType entType = (EntityType) type;
        if (!entType.getAssociatedEntityName().equals(entityName))
            continue;
        String[] cnames = childMeta.getPropertyColumnNames(i);
        if (cnames.length != colNames.length)
            continue;
        boolean columnMatch = true;
        for (int j = 0; j < cnames.length; j++) {
            if (!cnames[j].equals(colNames[j])) {
                columnMatch = false;
                break;
            }
        }
        if (columnMatch) {
            result[0] = childName;
            result[1] = propNames[i];
            return result;
        }
    }

    return null;
}

From source file:com.autobizlogic.abl.metadata.hibernate.HibMetaRole.java

License:Open Source License

/**
 * Get the inverse of a many-to-one role
 * @param entityName The entity owning the role
 * @param rName The role name/*from w  ww  . j  a v a  2s  .  c o m*/
 * @return Null if no inverse was found, otherwise [entity name, role name] of the inverse role
 */
private String[] getInverseOfSingleRole(String entityName, String rName) {
    String[] result = new String[2];

    SessionFactory sessFact = ((HibMetaModel) getMetaEntity().getMetaModel()).getSessionFactory();
    AbstractEntityPersister childMeta = (AbstractEntityPersister) sessFact.getClassMetadata(entityName);
    int propIdx = childMeta.getPropertyIndex(rName);
    String[] cnames = childMeta.getPropertyColumnNames(propIdx);
    Type parentType = childMeta.getPropertyType(rName);
    if (parentType instanceof OneToOneType)
        return getInverseOfOneToOneRole(entityName, rName);
    if (!(parentType instanceof ManyToOneType))
        throw new RuntimeException("Inverse of single-valued role " + entityName + "." + rName
                + " is neither single-valued not multi-valued");
    ManyToOneType manyType = (ManyToOneType) parentType;
    String parentEntityName = manyType.getAssociatedEntityName();

    AbstractEntityPersister parentMeta = (AbstractEntityPersister) sessFact.getClassMetadata(parentEntityName);
    String[] propNames = parentMeta.getPropertyNames();
    for (int i = 0; i < propNames.length; i++) {
        Type type = parentMeta.getPropertyType(propNames[i]);
        if (!type.isCollectionType())
            continue;
        CollectionType collType = (CollectionType) type;
        if (!collType.getAssociatedEntityName((SessionFactoryImplementor) sessFact).equals(entityName))
            continue;

        AbstractCollectionPersister persister = (AbstractCollectionPersister) sessFact
                .getCollectionMetadata(parentEntityName + "." + propNames[i]);
        String[] colNames = persister.getKeyColumnNames();
        if (cnames.length != colNames.length)
            continue;
        boolean columnMatch = true;
        for (int j = 0; j < cnames.length; j++) {
            if (!cnames[j].equals(colNames[j])) {
                columnMatch = false;
                break;
            }
        }
        if (columnMatch) {
            result[0] = parentEntityName;
            result[1] = propNames[i];
            return result;
        }
    }

    return null;
}

From source file:com.autobizlogic.abl.mgmt.ClassMetadataService.java

License:Open Source License

public static Map<String, Object> getMetadataForClass(Map<String, String> args) {
    String sessionFactoryId = args.get("sessionFactoryId");
    String name = args.get("className");
    HashMap<String, Object> result = new HashMap<String, Object>();

    SessionFactory factory = HibernateConfiguration.getSessionFactoryById(sessionFactoryId);
    if (factory == null)
        return null;

    ClassMetadata meta = factory.getClassMetadata(name);
    if (meta == null)
        return null;

    result.put("sessionFactoryId", sessionFactoryId);
    result.put("className", meta.getEntityName());
    result.put("identifierPropertyName", meta.getIdentifierPropertyName());

    Class<?> cls = meta.getMappedClass(EntityMode.POJO);
    Class<?> supercls = cls.getSuperclass();
    while (ProxyFactory.isProxyClass(supercls))
        supercls = supercls.getSuperclass();
    result.put("superclassName", supercls.getName());

    Map<String, String> properties = new HashMap<String, String>();
    Map<String, Object> collections = new HashMap<String, Object>();
    Map<String, String> associations = new HashMap<String, String>();

    String[] propNames = meta.getPropertyNames();
    Type[] propTypes = meta.getPropertyTypes();
    int i = 0;//from   w w  w  .  j  a  va2 s . com
    for (String propName : propNames) {
        if (propTypes[i].isCollectionType()) {
            CollectionType collType = (CollectionType) propTypes[i];
            Type elementType = collType.getElementType((SessionFactoryImplementor) factory);
            HashMap<String, String> collEntry = new HashMap<String, String>();
            collEntry.put("collectionType", collType.getReturnedClass().getName());
            collEntry.put("elementType", elementType.getName());
            collections.put(propName, collEntry);
        } else if (propTypes[i].isAssociationType()) {
            AssociationType assType = (AssociationType) propTypes[i];
            String assName = assType.getAssociatedEntityName((SessionFactoryImplementor) factory);
            associations.put(propName, assName);
        } else {
            properties.put(propName, propTypes[i].getName());
        }
        i++;
    }
    result.put("properties", properties);
    result.put("associations", associations);
    result.put("collections", collections);

    MetaModel metaModel = MetaModelFactory.getHibernateMetaModel(factory);
    LogicGroup logicGroup = RuleManager.getInstance(metaModel).getLogicGroupForClassName(name);
    if (logicGroup != null) {

        // Operations are actually actions and constraints
        List<Map<String, Object>> operations = new Vector<Map<String, Object>>();
        result.put("operations", operations);

        Set<ActionRule> actions = logicGroup.getActions();
        if (actions != null && actions.size() > 0) {
            for (ActionRule a : actions) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", a.getLogicMethodName());
                op.put("type", "action");
                operations.add(op);
            }
        }

        Set<EarlyActionRule> eactions = logicGroup.getEarlyActions();
        if (eactions != null && eactions.size() > 0) {
            for (EarlyActionRule a : eactions) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", a.getLogicMethodName());
                op.put("type", "early action");
                operations.add(op);
            }
        }

        Set<CommitActionRule> cactions = logicGroup.getCommitActions();
        if (cactions != null && cactions.size() > 0) {
            for (CommitActionRule a : cactions) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", a.getLogicMethodName());
                op.put("type", "commit action");
                operations.add(op);
            }
        }

        Set<ConstraintRule> constraints = logicGroup.getConstraints();
        if (constraints != null && constraints.size() > 0) {
            for (ConstraintRule constraint : constraints) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", constraint.getLogicMethodName());
                op.put("type", "constraint");
                operations.add(op);
            }
        }

        Set<CommitConstraintRule> cconstraints = logicGroup.getCommitConstraints();
        if (cconstraints != null && cconstraints.size() > 0) {
            for (ConstraintRule cconstraint : cconstraints) {
                Map<String, Object> op = new HashMap<String, Object>();
                op.put("name", cconstraint.getLogicMethodName());
                op.put("type", "commit constraint");
                operations.add(op);
            }
        }

        // Derivations are derived attributes
        Map<String, Object> derivations = new HashMap<String, Object>();
        result.put("derivations", derivations);

        Set<AbstractAggregateRule> aggregates = logicGroup.getAggregates();
        if (aggregates != null && aggregates.size() > 0) {
            for (AbstractAggregateRule aggregate : aggregates) {
                Map<String, Object> agg = new HashMap<String, Object>();
                if (aggregate instanceof CountRule)
                    agg.put("type", "count");
                else if (aggregate instanceof SumRule)
                    agg.put("type", "sum");
                else
                    agg.put("type", "unknown");
                agg.put("methodName", aggregate.getLogicMethodName());
                derivations.put(aggregate.getBeanAttributeName(), agg);
            }
        }

        List<FormulaRule> formulas = logicGroup.getFormulas();
        if (formulas != null && formulas.size() > 0) {
            for (FormulaRule formula : formulas) {
                Map<String, Object> form = new HashMap<String, Object>();
                form.put("type", "formula");
                form.put("methodName", formula.getLogicMethodName());
                derivations.put(formula.getBeanAttributeName(), form);
            }
        }

        Set<ParentCopyRule> pcRules = logicGroup.getParentCopies();
        if (pcRules != null && pcRules.size() > 0) {
            for (ParentCopyRule pcRule : pcRules) {
                Map<String, Object> parentCopy = new HashMap<String, Object>();
                parentCopy.put("type", "parent copy");
                parentCopy.put("methodName", pcRule.getLogicMethodName());
                derivations.put(pcRule.getChildAttributeName(), parentCopy);
            }
        }
    }

    HashMap<String, Object> finalResult = new HashMap<String, Object>();
    finalResult.put("data", result);

    return finalResult;
}

From source file:com.autobizlogic.abl.session.LogicTransactionContext.java

License:Open Source License

/**
 * Given an object, which could be either an entity or a proxy, get its primary key.
 *//*  w w  w  . ja  v a 2  s  . c  om*/
public Serializable getPrimaryKeyForObject(Object object) {
    if (object == null)
        return null;

    Serializable fk = null;
    if (object instanceof HibernateProxy) {
        HibernateProxy proxy = (HibernateProxy) object;
        fk = proxy.getHibernateLazyInitializer().getIdentifier();
    } else {
        SessionFactory sessionFactory = session.getSessionFactory();
        ClassMetadata classMeta = sessionFactory.getClassMetadata(object.getClass());
        fk = classMeta.getIdentifier(object, (SessionImplementor) session);
    }
    return fk;
}

From source file:com.eclecticlogic.pedal.provider.hibernate.HibernateProviderAccessSpiImpl.java

License:Apache License

/**
 * @param entityClass Entity class for which the table name is required.
 * @return Table name if the entity class is a single table.
 *//*from ww w.j a v a2 s.  c  o m*/
@Override
public String getTableName(Class<? extends Serializable> entityClass) {
    SessionFactory sf = emf.unwrap(HibernateEntityManagerFactory.class).getSessionFactory();
    ClassMetadata metadata = sf.getClassMetadata(entityClass);
    if (metadata instanceof SingleTableEntityPersister) {
        SingleTableEntityPersister step = (SingleTableEntityPersister) metadata;
        return step.getTableName();
    } else {
        return null;
    }
}