Example usage for org.hibernate.persister.entity EntityPersister getFactory

List of usage examples for org.hibernate.persister.entity EntityPersister getFactory

Introduction

In this page you can find the example usage for org.hibernate.persister.entity EntityPersister getFactory.

Prototype

SessionFactoryImplementor getFactory();

Source Link

Document

Return the SessionFactory to which this persister "belongs".

Usage

From source file:com.autobizlogic.abl.data.hibernate.HibPersistentBean.java

License:Open Source License

/**
 * Create from a persistent bean, either Pojo or Map.
 * @param bean A Hibernate persistent bean (can be a proxy)
 * @param pk The primary key for the given bean
 * @param persister The persister for the given bean.
 *///w  w w  . j  a v  a  2 s. c o  m
@SuppressWarnings("unchecked")
protected HibPersistentBean(Object bean, Serializable pk, EntityPersister persister, Session session) {

    if (bean instanceof Map) {
        try {
            this.map = (Map<String, Object>) bean;
        } catch (Exception ex) {
            throw new RuntimeException("Map is not Map<String, Object> for type " + persister.getEntityName());
        }
    } else {
        this.bean = getRawBean(bean);
        beanMap = new BeanMap(this.bean);
        map = beanMap;
    }
    this.pk = pk;

    this.metaEntity = MetaModelFactory.getHibernateMetaModel(persister.getFactory())
            .getMetaEntity(persister.getEntityName());
    this.session = session;
}

From source file:com.autobizlogic.abl.data.hibernate.HibPersistentBeanCopy.java

License:Open Source License

/**
 * Create from a persistent bean.//ww  w .j  a  v  a  2  s  .  c o m
 * @param bean A Hibernate persistent bean (can be a proxy) - either Pojo or Map, or even
 * a PersistentBean.
 * @param pk The primary key for the given bean
 * @param persister The persister for the given bean.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected HibPersistentBeanCopy(Object bean, Serializable pk, EntityPersister persister) {
    this.pk = pk;
    this.metaEntity = MetaModelFactory.getHibernateMetaModel(persister.getFactory())
            .getMetaEntity(persister.getEntityName());
    if (metaEntity == null)
        throw new RuntimeException("Could not find metadata from entity " + persister.getEntityName());

    if (bean instanceof HibPersistentBean) {
        HibPersistentBean pb = (HibPersistentBean) bean;
        this.bean = pb.bean;
        this.map = pb.map;
        this.beanMap = pb.beanMap;
    } else if (bean instanceof HibPersistentBeanCopy) {
        throw new RuntimeException("It makes no sense to make a copy of a HibPersistentBeanCopy");
    } else if (bean instanceof Map) {
        beanMap = (Map) bean;
        this.map = (Map<String, Object>) bean;
    } else {
        beanMap = new BeanMap(bean);
        this.bean = bean;
        map = beanMap;
    }

    if (map == null)
        throw new RuntimeException("No map defined for HibPersistentBeanCopy");

    // Copy all attributes
    for (MetaAttribute metaAttrib : metaEntity.getMetaAttributes()) {
        Object value = map.get(metaAttrib.getName());
        values.put(metaAttrib.getName(), value);
    }

    // Copy single-valued relationships
    for (MetaRole metaRole : metaEntity.getRolesFromChildToParents()) {
        String roleName = metaRole.getRoleName();
        Object value = map.get(roleName);
        values.put(roleName, value);
    }
}

From source file:com.autobizlogic.abl.data.hibernate.HibPersistentBeanCopy.java

License:Open Source License

/**
 * Create from a state array./*from  w w  w . j  a  v a2 s .  c  o m*/
 * @param The state (typically from a Hibernate event)
 * @param pk The primary key
 * @param persister The persister for the object
 */
@SuppressWarnings("unchecked")
protected HibPersistentBeanCopy(Object[] state, Object entity, Serializable pk, EntityPersister persister,
        Session session) {
    if (entity instanceof Map)
        map = (Map<String, Object>) entity;
    else {
        bean = entity;
        beanMap = new BeanMap(entity);
    }
    this.pk = pk;
    this.metaEntity = MetaModelFactory.getHibernateMetaModel(persister.getFactory())
            .getMetaEntity(persister.getEntityName());

    ClassMetadata metadata = persister.getClassMetadata();
    String[] propNames = metadata.getPropertyNames();
    for (int i = 0; i < propNames.length; i++) {
        String propName = propNames[i];
        if (metaEntity.getMetaProperty(propName).isCollection())
            continue;

        MetaRole metaRole = metaEntity.getMetaRole(propName);
        if (metaRole == null) { // Not a relationship -- must be an attribute
            if (state[i] != null)
                values.put(propName, state[i]);
        } else if (!metaRole.isCollection()) {
            // In the case of old values, when we are handed the state, it contains the pk for associations,
            // and not (as you'd expect) the object itself. So we check whether the value is a real object,
            // and if it's not, we grab it from the object.
            if (state[i] == null || session.contains(state[i])) {
                values.put(propName, state[i]);
            } else {
                // We have a pk instead of a proxy -- ask Hibernate to create a proxy for it.
                String className = metadata.getPropertyType(propName).getReturnedClass().getName();
                PersistenceContext persContext = HibernateSessionUtil.getPersistenceContextForSession(session);
                EntityPersister entityPersister = HibernateSessionUtil.getEntityPersister(session, className,
                        bean);
                EntityKey entityKey = new EntityKey((Serializable) state[i], entityPersister,
                        session.getEntityMode());

                // Has a proxy already been created for this session?
                Object proxy = persContext.getProxy(entityKey);
                if (proxy == null) {
                    // There is no proxy anywhere for this object, so ask Hibernate to create one for us
                    proxy = entityPersister.createProxy((Serializable) state[i], (SessionImplementor) session);
                    persContext.getBatchFetchQueue().addBatchLoadableEntityKey(entityKey);
                    persContext.addProxy(entityKey, proxy);
                }
                values.put(propName, proxy);
            }
        }
    }
}

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

License:Open Source License

/**
 * Get the value of the identifier for the given entity, whatever its type (Pojo or Map).
 * @param entity The entity/*from w w w.ja v a  2  s  . c  o  m*/
 * @param persister The entity's persister
 * @return The identifier for the entity
 */
public static Serializable getPrimaryKeyForEntity(Object entity, EntityPersister persister) {

    String entityName = persister.getEntityName();
    MetaModel metaModel = MetaModelFactory.getHibernateMetaModel(persister.getFactory());
    MetaEntity metaEntity = metaModel.getMetaEntity(entityName);
    String pkName = metaEntity.getIdentifierName();
    if (entity instanceof Map) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) entity;
        return (Serializable) map.get(pkName);
    }
    BeanMap beanMap = new BeanMap(entity);
    return (Serializable) beanMap.get(pkName);
}

From source file:com.corundumstudio.hibernate.dsc.QueryCacheEntityListener.java

License:Apache License

private DynamicQueryCache getQueryCache(EntityPersister persister, String regionName,
        QueryListenerEntry listenerValue) {
    return (DynamicQueryCache) persister.getFactory().getQueryCache(regionName);
}

From source file:edu.utah.further.core.data.hibernate.listeners.PreUpdatePreventNullOverwriteListener.java

License:Apache License

@SuppressWarnings("resource")
@Override//from w ww  .j a v  a 2s  .  c  o  m
public boolean onPreUpdate(final PreUpdateEvent event) {
    if (log.isDebugEnabled()) {
        log.debug("Received pre-update event");
    }
    final EntityPersister entityPersister = event.getPersister();
    final EntityMode entityMode = entityPersister.guessEntityMode(event.getEntity());
    final Connection connection = getConnection(entityPersister);
    final StatelessSession session = entityPersister.getFactory().openStatelessSession(connection);
    session.beginTransaction();
    final Serializable entityId = entityPersister.getIdentifier(event.getEntity(),
            (SessionImplementor) session);
    final Object existingEntity = session.get(event.getEntity().getClass(), entityId);

    if (log.isDebugEnabled()) {
        log.debug("Loaded existing entity " + existingEntity);
    }

    boolean updatedExistingEntity = false;
    for (int i = 0; i < entityPersister.getPropertyNames().length; i++) {
        final Object oldPropValue = entityPersister.getPropertyValue(existingEntity, i, entityMode);
        if (oldPropValue == null) {

            if (log.isDebugEnabled()) {
                log.debug("Found a property in the existing " + "entity that was null, checking new entity");
            }

            final Object newPropValue = entityPersister.getPropertyValue(event.getEntity(), i, entityMode);

            if (!(newPropValue instanceof Collection<?>) && newPropValue != null) {

                if (log.isDebugEnabled()) {
                    log.debug("The new entity contains a non-null " + "value, updating existing entity");
                }

                entityPersister.setPropertyValue(existingEntity, i, newPropValue, entityMode);
                updatedExistingEntity = true;
            }
        }
    }

    if (updatedExistingEntity) {
        entityPersister.getFactory().getCurrentSession().cancelQuery();
        session.update(existingEntity);
    }

    session.getTransaction().commit();
    session.close();

    return updatedExistingEntity;
}

From source file:edu.utah.further.core.data.hibernate.listeners.PreUpdatePreventNullOverwriteListener.java

License:Apache License

/**
 * @param entityPersister/*ww  w.j  a va  2  s  .  co m*/
 * @return
 */
private Connection getConnection(final EntityPersister entityPersister) {
    Connection connection;
    try {
        connection = entityPersister.getFactory().getConnectionProvider().getConnection();
    } catch (final SQLException e) {
        throw new ApplicationException(
                "Unable to retrieve the connection during PreUpdatePreventNullOverwriteListener");
    }
    return connection;
}

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;
    }//w ww .  java2  s. 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.tonguetied.audit.AuditLogPostDeleteEventListener.java

License:Apache License

/**
 * Add an entry in the audit log for the removal of an {@link Auditable} 
 * entity./*from  ww  w  . j av a2  s. c om*/
 */
public void onPostDelete(final PostDeleteEvent event) {
    if (event.getEntity() instanceof Auditable) {
        Auditable entity = (Auditable) event.getEntity();
        if (logger.isDebugEnabled())
            logger.debug("Adding an audit log entry for deletion of entity " + entity.getClass() + " with id "
                    + entity.getId());

        final Object[] deletedState = event.getDeletedState();
        final EntityPersister persister = event.getPersister();
        processEntity(deletedState, null, persister);
        AuditLog.logEvent(Operation.delete, entity, getNewValue(), getOldValue(), persister.getFactory());
    }
}

From source file:org.tonguetied.audit.AuditLogPostInsertEventListener.java

License:Apache License

/**
 * Add an entry in the audit log for the creation of an {@link Auditable} 
 * entity.// ww w . ja  v a  2  s .c  o m
 */
public void onPostInsert(final PostInsertEvent event) {
    if (event.getEntity() instanceof Auditable) {
        final Auditable entity = (Auditable) event.getEntity();
        if (logger.isDebugEnabled())
            logger.debug("Adding an audit log entry for insertion of entity " + entity.getClass() + " with id "
                    + entity.getId());
        final Object[] state = event.getState();
        final EntityPersister persister = event.getPersister();
        processEntity(null, state, persister);

        AuditLog.logEvent(Operation.insert, entity, getNewValue(), getOldValue(), persister.getFactory());
    }
}