Example usage for org.hibernate EntityMode POJO

List of usage examples for org.hibernate EntityMode POJO

Introduction

In this page you can find the example usage for org.hibernate EntityMode POJO.

Prototype

EntityMode POJO

To view the source code for org.hibernate EntityMode POJO.

Click Source Link

Document

The pojo entity mode describes an entity model made up of entity classes (loosely) following the java bean convention.

Usage

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);
    }//  ww w . j  a v a  2 s.  c  o  m
    configureInheritanceMappings(hibernateDomainClassMap);
}

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

License:Apache License

@Override
public void destroy() throws HibernateException {
    MetaClassRegistry registry = GroovySystem.getMetaClassRegistry();
    Map<?, ?> classMetaData = getSessionFactory().getAllClassMetadata();
    for (Object o : classMetaData.values()) {
        ClassMetadata classMetadata = (ClassMetadata) o;
        Class<?> mappedClass = classMetadata.getMappedClass(EntityMode.POJO);
        registry.removeMetaClass(mappedClass);
    }/*w  w w.j  a  v  a 2s.  c o m*/
    super.destroy();
}

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

License:Apache License

/**
 * Contructor to be used by all child classes to create a new instance
 * and get the name right.//from  w w  w. j a va2s .c o m
 *
 * @param clazz          the Grails class
 * @param sessionFactory The Hibernate SessionFactory instance
 * @param metaData       The ClassMetaData for this class retrieved from the SF
 */
public GrailsHibernateDomainClass(Class<?> clazz, SessionFactory sessionFactory, GrailsApplication application,
        ClassMetadata metaData) {
    super(clazz, "");
    this.application = application;

    new StandardAnnotationMetadata(clazz);
    String ident = metaData.getIdentifierPropertyName();
    if (ident != null) {
        Class<?> identType = getPropertyType(ident);
        identifier = new GrailsHibernateDomainClassProperty(this, ident);
        identifier.setIdentity(true);
        identifier.setType(identType);
        propertyMap.put(ident, identifier);
    }

    // configure the version property
    final int versionIndex = metaData.getVersionProperty();
    String versionPropertyName = null;
    if (versionIndex > -1) {
        versionPropertyName = metaData.getPropertyNames()[versionIndex];
        version = new GrailsHibernateDomainClassProperty(this, versionPropertyName);
        version.setType(getPropertyType(versionPropertyName));
    }

    // configure remaining properties
    String[] propertyNames = metaData.getPropertyNames();
    for (String propertyName : propertyNames) {
        if (!propertyName.equals(ident)
                && !(versionPropertyName != null && propertyName.equals(versionPropertyName))) {
            GrailsHibernateDomainClassProperty prop = new GrailsHibernateDomainClassProperty(this,
                    propertyName);
            prop.setType(getPropertyType(propertyName));
            Type hibernateType = metaData.getPropertyType(propertyName);

            // if its an association type
            if (hibernateType.isAssociationType()) {
                prop.setAssociation(true);
                // get the associated type from the session factory and set it on the property
                AssociationType assType = (AssociationType) hibernateType;
                if (assType instanceof AnyType) {
                    continue;
                }
                try {
                    String associatedEntity = assType
                            .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
                    ClassMetadata associatedMetaData = sessionFactory.getClassMetadata(associatedEntity);
                    prop.setRelatedClassType(associatedMetaData.getMappedClass(EntityMode.POJO));
                } catch (MappingException me) {
                    // other side must be a value object
                    if (hibernateType.isCollectionType()) {
                        prop.setRelatedClassType(Collection.class);
                    }
                }
                // configure type of relationship
                if (hibernateType.isCollectionType()) {
                    prop.setOneToMany(true);
                } else if (hibernateType.isEntityType()) {
                    prop.setManyToOne(true);
                    // might not really be true, but for our purposes this is ok
                    prop.setOneToOne(true);
                }
            }
            propertyMap.put(propertyName, prop);
        }
    }

    properties = propertyMap.values().toArray(new GrailsDomainClassProperty[propertyMap.size()]);
    // process the constraints
    evaluateConstraints();
}

From source file:org.codehaus.groovy.grails.orm.hibernate.support.ClosureEventListener.java

License:Apache License

private void synchronizePersisterState(Object entity, EntityPersister persister, Object[] state) {
    String[] propertyNames = persister.getPropertyNames();
    for (int i = 0; i < propertyNames.length; i++) {
        String p = propertyNames[i];
        MetaProperty metaProperty = domainMetaClass.getMetaProperty(p);
        if (ClosureEventTriggeringInterceptor.IGNORED.contains(p) || metaProperty == null) {
            continue;
        }//from  w  w  w . ja va 2 s. co  m
        Object value = metaProperty.getProperty(entity);
        state[i] = value;
        persister.setPropertyValue(entity, i, value, EntityMode.POJO);
    }
}

From source file:org.compass.gps.device.hibernate.dep.Hibernate3GpsDevice.java

License:Apache License

protected HibernateEntityInfo[] doGetHibernateEntitiesInfo() throws HibernateGpsDeviceException {
    ArrayList infos = new ArrayList();
    try {//from  w w w . j  a  v  a  2s.c o  m
        Map allClassMetaData = sessionFactory.getAllClassMetadata();
        for (Iterator it = allClassMetaData.keySet().iterator(); it.hasNext();) {
            String entityname = (String) it.next();
            ClassMetadata classMetadata = (ClassMetadata) allClassMetaData.get(entityname);
            // if it is inherited, do not add it to the classes to index, since the "from [entity]"
            // query for the base class will return results for this class as well
            if (isInherited(classMetadata)) {
                String superClassEntityName = ((AbstractEntityPersister) classMetadata).getMappedSuperclass();
                ClassMetadata superClassMetadata = (ClassMetadata) allClassMetaData.get(superClassEntityName);
                Class superClass = superClassMetadata.getMappedClass(EntityMode.POJO);
                // only filter out classes that their super class has compass mappings
                if (superClass != null && compassGps.hasMappingForEntityForIndex(superClass)) {
                    if (log.isDebugEnabled()) {
                        log.debug(buildMessage("entity [" + entityname + "] is inherited and super class ["
                                + superClass + "] has compass mapping, filtering it out"));
                    }
                    continue;
                }
            }
            if (isFilteredForIndex(entityname)) {
                if (log.isDebugEnabled()) {
                    log.debug(buildMessage(
                            "entity [" + entityname + "] is marked to be filtered, filtering it out"));
                }
                continue;
            }
            if (compassGps.hasMappingForEntityForIndex((entityname))) {
                ResourceMapping resourceMapping = compassGps.getMappingForEntityForIndex(entityname);
                HibernateEntityInfo info = new HibernateEntityInfo(entityname, "from " + entityname,
                        resourceMapping.getSubIndexHash().getSubIndexes());
                infos.add(info);
                if (log.isDebugEnabled()) {
                    log.debug(buildMessage("entity [" + entityname + "] will be indexed"));
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(buildMessage(
                            "entity [" + entityname + "] does not have compass mapping, filtering it out"));
                }
            }
        }
    } catch (Exception e) {
        throw new HibernateGpsDeviceException(buildMessage("Failed to fetch all class meta data"), e);
    }

    return (HibernateEntityInfo[]) infos.toArray(new HibernateEntityInfo[infos.size()]);
}

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 ww  .  j av a  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.hibernate.entities.DefaultHibernateEntitiesLocator.java

License:Apache License

/**
 * Returns <code>true</code> if the entity name needs to be filtered.
 *
 * <p>Implementation filteres out inherited hibernate mappings, since the select query
 * for the base class will cover any inherited classes as well.
 *
 * <p>Note, that this method is called after it has been verified that the class has
 * Compass mappings (either directly, or indirectly by an interface or a super class).
 *
 * @param entityname    The name of the entity
 * @param classMetadata The Hibernate class meta data.
 * @param device        The Hibernate Gps device
 * @return <code>true</code> if the entity should be filtered out, <code>false</code> if not.
 */// w  ww.  j a v a  2s  .  c om
protected boolean shouldFilter(String entityname, ClassMetadata classMetadata, Map allClassMetaData,
        HibernateGpsDevice device) {
    Class clazz = classMetadata.getMappedClass(EntityMode.POJO);
    // if it is inherited, do not add it to the classes to index, since the "from [entity]"
    // query for the base class will return results for this class as well
    if (classMetadata.isInherited()) {
        String superClassEntityName = ((AbstractEntityPersister) classMetadata).getMappedSuperclass();
        ClassMetadata superClassMetadata = (ClassMetadata) allClassMetaData.get(superClassEntityName);
        Class superClass = superClassMetadata.getMappedClass(EntityMode.POJO);
        // only filter out classes that their super class has compass mappings
        if (superClass != null
                && ((CompassGpsInterfaceDevice) device.getGps()).hasMappingForEntityForIndex(superClass)) {
            if (log.isDebugEnabled()) {
                log.debug("Entity [" + entityname + "] is inherited and super class [" + superClass
                        + "] has compass mapping, filtering it out");
            }
            return true;
        }
    }
    return false;
}

From source file:org.compass.gps.device.hibernate.lifecycle.HibernateEventListenerUtils.java

License:Apache License

public static Collection getUnpersistedCascades(CompassGpsInterfaceDevice compassGps, Object entity,
        SessionFactoryImplementor sessionFactory, Cascade cascade, Collection visited) {
    if (visited.contains(entity)) {
        return Collections.EMPTY_SET;
    }/*from   ww  w  .  j  a  v a  2s .  c o m*/
    visited.add(entity);

    ClassMetadata classMetadata = sessionFactory.getClassMetadata(entity.getClass());
    if (classMetadata == null) {
        for (Iterator iter = sessionFactory.getAllClassMetadata().values().iterator(); iter.hasNext();) {
            ClassMetadata temp = (ClassMetadata) iter.next();
            if (entity.getClass().equals(temp.getMappedClass(EntityMode.POJO))) {
                classMetadata = temp;
                break;
            }
        }
    }
    Assert.notNull(classMetadata, "Failed to lookup Hibernate ClassMetadata for entity [" + entity + "]");
    String entityName = classMetadata.getEntityName();
    EntityPersister persister = sessionFactory.getEntityPersister(entityName);

    CompassMapping compassMapping = ((InternalCompass) compassGps.getIndexCompass()).getMapping();
    ClassMapping classMapping = (ClassMapping) compassMapping.getMappingByClass(entity.getClass());
    if (classMapping == null) {
        return Collections.EMPTY_SET;
    }

    //        CascadeStyle[] cascadeStyles = persister.getEntityMetamodel().getCascadeStyles();
    String[] propertyNames = persister.getPropertyNames();
    Type[] types = persister.getPropertyTypes();
    Set dependencies = new HashSet();
    for (int i = 0, len = propertyNames.length; i < len; i++) {
        // property cascade includes save/update?
        //            CascadeStyle cascadeStyle = cascadeStyles[i];
        //            if (!cascadeStyle.doCascade(CascadingAction.SAVE_UPDATE)) {
        //                continue;
        //            }
        // property is mapped in Compass?
        String name = propertyNames[i];
        Mapping mapping = classMapping.getMapping(name);
        if (mapping == null) {
            continue;
        }
        // property value is not null?
        Object propertyValue = persister.getPropertyValue(entity, name, EntityMode.POJO);
        if (propertyValue == null) {
            continue;
        }
        // find actual property type
        // todo may not be correct see http://www.hibernate.org/hib_docs/v3/api/org/hibernate/type/EntityType.html#getReturnedClass()
        // todo may need to use class name string comparison instead
        Class propertyType;
        Type type = types[i];
        boolean collection = false;
        if (type instanceof CollectionType) {
            CollectionType collectionType = (CollectionType) type;
            propertyType = persister.getFactory().getCollectionPersister(collectionType.getRole())
                    .getElementType().getReturnedClass();
            collection = true;
        } else {
            propertyType = type.getReturnedClass();
        }
        // Mirroring is cascaded for this property?
        if (!compassGps.hasMappingForEntityForMirror(propertyType, cascade)) {
            continue;
        }
        // find dependent unpersisted property value(s)
        ResourceMapping propertyTypeMapping = compassMapping.getMappingByClass(propertyType);
        Mapping[] idMappings = propertyTypeMapping.getIdMappings();
        for (int j = 0, jlen = idMappings.length; j < jlen; j++) {
            ClassPropertyMetaDataMapping idMapping = (ClassPropertyMetaDataMapping) idMappings[j];
            try {
                // initiaize the value in case it is lazy (and only for the first time)
                if (j == 0) {
                    if (propertyValue instanceof HibernateProxy) {
                        propertyValue = ((HibernateProxy) propertyValue).getHibernateLazyInitializer()
                                .getImplementation();
                    }
                }
                if (collection) {
                    for (Iterator iter = ((Collection) propertyValue).iterator(); iter.hasNext();) {
                        Object obj = iter.next();
                        Object id = idMapping.getGetter().get(obj);
                        if (id == null) {
                            dependencies.add(obj);
                        }
                        dependencies.addAll(
                                getUnpersistedCascades(compassGps, obj, sessionFactory, cascade, visited));
                    }
                } else {
                    Object id = idMapping.getGetter().get(propertyValue);
                    if (id == null) {
                        dependencies.add(propertyValue);
                    }
                    dependencies.addAll(getUnpersistedCascades(compassGps, propertyValue, sessionFactory,
                            cascade, visited));
                }
            } catch (Exception e) {
                // ignore
            }
        }
    }
    return dependencies;
}

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   www . jav  a  2s.  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,
                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()]);
}

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

License:Apache License

/**
 * Returns <code>true</code> if the entity name needs to be filtered.
 *
 * <p>Implementation filteres out inherited hibernate mappings, since the select query
 * for the base class will cover any inherited classes as well.
 *
 * <p>Note, that this method is called after it has been verified that the class has
 * Compass mappings (either directly, or indirectly by an interface or a super class).
 *
 * @param entityname    The name of the entity
 * @param classMetadata The Hibernate class meta data.
 * @param device        The Jpa Gps device
 * @return <code>true</code> if the entity should be filtered out, <code>false</code> if not.
 *//*from  w  ww  .  j a v  a 2  s.c o m*/
protected boolean shouldFilter(String entityname, ClassMetadata classMetadata, Map allClassMetaData,
        JpaGpsDevice device) {
    Class<?> clazz = classMetadata.getMappedClass(EntityMode.POJO);
    // if it is inherited, do not add it to the classes to index, since the "from [entity]"
    // query for the base class will return results for this class as well
    if (classMetadata.isInherited()) {
        String superClassEntityName = ((AbstractEntityPersister) classMetadata).getMappedSuperclass();
        ClassMetadata superClassMetadata = (ClassMetadata) allClassMetaData.get(superClassEntityName);
        Class superClass = superClassMetadata.getMappedClass(EntityMode.POJO);
        // only filter out classes that their super class has compass mappings
        if (superClass != null
                && ((CompassGpsInterfaceDevice) device.getGps()).hasMappingForEntityForIndex(superClass)) {
            if (log.isDebugEnabled()) {
                log.debug("Entity [" + entityname + "] is inherited and super class [" + superClass
                        + "] has compass mapping, filtering it out");
            }
            return true;
        }
    }
    return false;
}