Example usage for org.hibernate EntityMode MAP

List of usage examples for org.hibernate EntityMode MAP

Introduction

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

Prototype

EntityMode MAP

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

Click Source Link

Document

The dynamic-map entity mode describes an entity model defined using java.util.Map references.

Usage

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

License:Open Source License

public EntityType getEntityType() {

    if (entityType != null)
        return entityType;

    EntityMode entityMode = ((SessionFactoryImpl) sessionFactory).getSettings().getDefaultEntityMode();
    if (entityMode.equals(EntityMode.POJO))
        entityType = EntityType.POJO;//from w w  w.j a  va2s.co  m
    else if (entityMode.equals(EntityMode.MAP))
        entityType = EntityType.MAP;
    else
        throw new RuntimeException("Hibernate session factory has a default entity mode of " + entityMode
                + ", which is neither POJO nor MAP. This is not supported.");

    return entityType;
}

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  ava 2s  . co  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.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

/**
 * @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
 *///from   w  w  w.  j  av a 2  s  .  c  om
@Deprecated
public void saveXWikiCollection(BaseCollection object, XWikiContext context, boolean bTransaction)
        throws XWikiException {
    try {
        if (object == null) {
            return;
        }
        // We need a slightly different behavior here
        boolean stats = (object instanceof XWikiStats);

        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(context);
        }
        Session session = getSession(context);

        // Verify if the property already exists
        Query query;
        if (stats) {
            query = session.createQuery(
                    "select obj.id from " + object.getClass().getName() + " as obj where obj.id = :id");
        } else {
            query = session.createQuery("select obj.id from BaseObject as obj where obj.id = :id");
        }
        query.setInteger("id", object.getId());
        if (query.uniqueResult() == null) {
            if (stats) {
                session.save(object);
            } else {
                session.save("com.xpn.xwiki.objects.BaseObject", object);
            }
        } else {
            if (stats) {
                session.update(object);
            } else {
                session.update("com.xpn.xwiki.objects.BaseObject", object);
            }
        }
        /*
         * if (stats) session.saveOrUpdate(object); else
         * session.saveOrUpdate((String)"com.xpn.xwiki.objects.BaseObject", (Object)object);
         */
        BaseClass bclass = object.getXClass(context);
        List<String> handledProps = new ArrayList<String>();
        if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
            // save object using the custom mapping
            Map<String, Object> objmap = object.getCustomMappingMap();
            handledProps = bclass.getCustomMappingPropertyList(context);
            Session dynamicSession = session.getSession(EntityMode.MAP);
            query = session
                    .createQuery("select obj.id from " + bclass.getName() + " as obj where obj.id = :id");
            query.setInteger("id", object.getId());
            if (query.uniqueResult() == null) {
                dynamicSession.save(bclass.getName(), objmap);
            } else {
                dynamicSession.update(bclass.getName(), objmap);
            }

            // dynamicSession.saveOrUpdate((String) bclass.getName(), objmap);
        }

        if (object.getXClassReference() != null) {
            // Remove all existing properties
            if (object.getFieldsToRemove().size() > 0) {
                for (int i = 0; i < object.getFieldsToRemove().size(); i++) {
                    BaseProperty prop = (BaseProperty) object.getFieldsToRemove().get(i);
                    if (!handledProps.contains(prop.getName())) {
                        session.delete(prop);
                    }
                }
                object.setFieldsToRemove(new ArrayList<BaseProperty>());
            }

            Iterator<String> it = object.getPropertyList().iterator();
            while (it.hasNext()) {
                String key = it.next();
                BaseProperty prop = (BaseProperty) object.getField(key);
                if (!prop.getName().equals(key)) {
                    Object[] args = { key, object.getName() };
                    throw new XWikiException(XWikiException.MODULE_XWIKI_CLASSES,
                            XWikiException.ERROR_XWIKI_CLASSES_FIELD_INVALID,
                            "Field {0} in object {1} has an invalid name", null, args);
                }

                String pname = prop.getName();
                if (pname != null && !pname.trim().equals("") && !handledProps.contains(pname)) {
                    saveXWikiProperty(prop, context, false);
                }
            }
        }

        if (bTransaction) {
            endTransaction(context, true);
        }
    } catch (XWikiException xe) {
        throw xe;
    } catch (Exception e) {
        Object[] args = { object.getName() };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_OBJECT, "Exception while saving object {0}",
                e, args);

    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, true);
            }
        } catch (Exception e) {
        }
    }
}

From source file:com.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

/**
 * @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
 *///from   w  ww.  j ava  2  s.c o m
@Deprecated
public void loadXWikiCollection(BaseCollection object1, XWikiDocument doc, XWikiContext context,
        boolean bTransaction, boolean alreadyLoaded) throws XWikiException {
    BaseCollection object = object1;
    try {
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(false, context);
        }
        Session session = getSession(context);

        if (!alreadyLoaded) {
            try {
                session.load(object, Integer.valueOf(object1.getId()));
            } catch (ObjectNotFoundException e) {
                // There is no object data saved
                object = null;
                return;
            }
        }

        DocumentReference classReference = object.getXClassReference();

        // If the class reference is null in the loaded object then skip loading properties
        if (classReference != null) {

            BaseClass bclass = null;
            if (!classReference.equals(object.getDocumentReference())) {
                // Let's check if the class has a custom mapping
                bclass = object.getXClass(context);
            } else {
                // We need to get it from the document otherwise
                // we will go in an endless loop
                if (doc != null) {
                    bclass = doc.getXClass();
                }
            }

            List<String> handledProps = new ArrayList<String>();
            try {
                if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
                    Session dynamicSession = session.getSession(EntityMode.MAP);
                    Object map = dynamicSession.load(bclass.getName(), Integer.valueOf(object.getId()));
                    // Let's make sure to look for null fields in the dynamic mapping
                    bclass.fromValueMap((Map) map, object);
                    handledProps = bclass.getCustomMappingPropertyList(context);
                    for (String prop : handledProps) {
                        if (((Map) map).get(prop) == null) {
                            handledProps.remove(prop);
                        }
                    }
                }
            } catch (Exception e) {
            }

            // Load strings, integers, dates all at once

            Query query = session.createQuery(
                    "select prop.name, prop.classType from BaseProperty as prop where " + "prop.id.id = :id");
            query.setInteger("id", object.getId());
            for (Object[] result : (List<Object[]>) query.list()) {
                String name = (String) result[0];
                // No need to load fields already loaded from
                // custom mapping
                if (handledProps.contains(name)) {
                    continue;
                }
                String classType = (String) result[1];
                BaseProperty property = null;

                try {
                    property = (BaseProperty) Class.forName(classType).newInstance();
                    property.setObject(object);
                    property.setName(name);
                    loadXWikiProperty(property, context, false);
                } catch (Exception e) {
                    // WORKAROUND IN CASE OF MIXMATCH BETWEEN STRING AND LARGESTRING
                    try {
                        if (property instanceof StringProperty) {
                            LargeStringProperty property2 = new LargeStringProperty();
                            property2.setObject(object);
                            property2.setName(name);
                            loadXWikiProperty(property2, context, false);
                            property.setValue(property2.getValue());

                            if (bclass != null) {
                                if (bclass.get(name) instanceof TextAreaClass) {
                                    property = property2;
                                }
                            }

                        } else if (property instanceof LargeStringProperty) {
                            StringProperty property2 = new StringProperty();
                            property2.setObject(object);
                            property2.setName(name);
                            loadXWikiProperty(property2, context, false);
                            property.setValue(property2.getValue());

                            if (bclass != null) {
                                if (bclass.get(name) instanceof StringClass) {
                                    property = property2;
                                }
                            }
                        } else {
                            throw e;
                        }
                    } catch (Throwable e2) {
                        Object[] args = { object.getName(), object.getClass(),
                                Integer.valueOf(object.getNumber() + ""), name };
                        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
                                "Exception while loading object '{0}' of class '{1}', number '{2}' and property '{3}'",
                                e, args);
                    }
                }

                object.addField(name, property);
            }
        }

        if (bTransaction) {
            endTransaction(context, false, false);
        }
    } catch (Exception e) {
        Object[] args = { object.getName(), object.getClass(), Integer.valueOf(object.getNumber() + "") };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT,
                "Exception while loading object '{0}' of class '{1}' and number '{2}'", e, args);

    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false, false);
            }
        } catch (Exception e) {
        }
    }

}

From source file:com.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

/**
 * @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
 *///from w  w w .ja  va 2  s . c o m
@Deprecated
public void deleteXWikiCollection(BaseCollection object, XWikiContext context, boolean bTransaction,
        boolean evict) throws XWikiException {
    if (object == null) {
        return;
    }
    try {
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(context);
        }
        Session session = getSession(context);

        // Let's check if the class has a custom mapping
        BaseClass bclass = object.getXClass(context);
        List<String> handledProps = new ArrayList<String>();
        if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
            handledProps = bclass.getCustomMappingPropertyList(context);
            Session dynamicSession = session.getSession(EntityMode.MAP);
            Object map = dynamicSession.get(bclass.getName(), Integer.valueOf(object.getId()));
            if (map != null) {
                if (evict) {
                    dynamicSession.evict(map);
                }
                dynamicSession.delete(map);
            }
        }

        if (object.getXClassReference() != null) {
            for (BaseElement property : (Collection<BaseElement>) object.getFieldList()) {
                if (!handledProps.contains(property.getName())) {
                    if (evict) {
                        session.evict(property);
                    }
                    if (session.get(property.getClass(), property) != null) {
                        session.delete(property);
                    }
                }
            }
        }

        // In case of custom class we need to force it as BaseObject to delete the xwikiobject row
        if (!"".equals(bclass.getCustomClass())) {
            BaseObject cobject = new BaseObject();
            cobject.setDocumentReference(object.getDocumentReference());
            cobject.setClassName(object.getClassName());
            cobject.setNumber(object.getNumber());
            if (object instanceof BaseObject) {
                cobject.setGuid(((BaseObject) object).getGuid());
            }
            cobject.setId(object.getId());
            if (evict) {
                session.evict(cobject);
            }
            session.delete(cobject);
        } else {
            if (evict) {
                session.evict(object);
            }
            session.delete(object);
        }

        if (bTransaction) {
            endTransaction(context, true);
        }
    } catch (Exception e) {
        Object[] args = { object.getName() };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_OBJECT,
                "Exception while deleting object {0}", e, args);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false);
            }
        } catch (Exception e) {
        }
    }
}

From source file:lucee.runtime.orm.hibernate.HibernateORMEngine.java

License:Open Source License

private SessionFactoryData getSessionFactoryData(PageContext pc, int initType) throws PageException {
    ApplicationContextPro appContext = (ApplicationContextPro) pc.getApplicationContext();
    if (!appContext.isORMEnabled())
        throw ExceptionUtil.createException((ORMSession) null, null, "ORM is not enabled", "");

    // datasource
    ORMConfiguration ormConf = appContext.getORMConfiguration();
    String key = hash(ormConf);/*from w  ww .  j av  a  2  s .  co  m*/
    SessionFactoryData data = factories.get(key);
    if (initType == INIT_ALL && data != null) {
        data.reset();
        data = null;
    }
    if (data == null) {
        data = new SessionFactoryData(this, ormConf);
        factories.put(key, data);
    }

    // config
    try {
        //arr=null;
        if (initType != INIT_NOTHING) {
            synchronized (data) {

                if (ormConf.autogenmap()) {
                    data.tmpList = HibernateSessionFactory.loadComponents(pc, this, ormConf);

                    data.clearCFCs();
                } else
                    throw ExceptionUtil.createException(data, null,
                            "orm setting autogenmap=false is not supported yet", null);

                // load entities
                if (data.tmpList != null && data.tmpList.size() > 0) {
                    data.getNamingStrategy();// called here to make sure, it is called in the right context the first one

                    // creates CFCInfo objects
                    {
                        Iterator<Component> it = data.tmpList.iterator();
                        while (it.hasNext()) {
                            createMapping(pc, it.next(), ormConf, data);
                        }
                    }

                    if (data.tmpList.size() != data.sizeCFCs()) {
                        Component cfc;
                        String name, lcName;
                        Map<String, String> names = new HashMap<String, String>();
                        Iterator<Component> it = data.tmpList.iterator();
                        while (it.hasNext()) {
                            cfc = it.next();
                            name = HibernateCaster.getEntityName(cfc);
                            lcName = name.toLowerCase();
                            if (names.containsKey(lcName))
                                throw ExceptionUtil.createException(data, null,
                                        "Entity Name [" + name + "] is ambigous, [" + names.get(lcName)
                                                + "] and [" + cfc.getPageSource().getDisplayPath()
                                                + "] use the same entity name.",
                                        "");
                            names.put(lcName, cfc.getPageSource().getDisplayPath());
                        }
                    }
                }
            }
        }
    } finally {
        data.tmpList = null;
    }

    // already initialized for this application context

    //MUST
    //cacheconfig
    //cacheprovider
    //...

    Log log = ((ConfigImpl) pc.getConfig()).getLog("orm");

    Iterator<Entry<Key, String>> it = HibernateSessionFactory.createMappings(ormConf, data).entrySet()
            .iterator();
    Entry<Key, String> e;
    while (it.hasNext()) {
        e = it.next();
        if (data.getConfiguration(e.getKey()) != null)
            continue;

        DatasourceConnection dc = CommonUtil.getDatasourceConnection(pc, data.getDataSource(e.getKey()));
        try {
            data.setConfiguration(log, e.getValue(), dc);
        } catch (Exception ex) {
            throw CommonUtil.toPageException(ex);
        } finally {
            CommonUtil.releaseDatasourceConnection(pc, dc);
        }
        addEventListeners(pc, data, e.getKey());

        EntityTuplizerFactory tuplizerFactory = data.getConfiguration(e.getKey()).getEntityTuplizerFactory();
        tuplizerFactory.registerDefaultTuplizerClass(EntityMode.MAP, AbstractEntityTuplizerImpl.class);
        tuplizerFactory.registerDefaultTuplizerClass(EntityMode.POJO, AbstractEntityTuplizerImpl.class);

        data.buildSessionFactory(e.getKey());
    }

    return data;
}

From source file:lucee.runtime.orm.hibernate.tuplizer.AbstractEntityTuplizerImpl.java

License:Open Source License

public EntityMode getEntityMode() {
    return EntityMode.MAP;
}

From source file:org.eclipse.emf.teneo.hibernate.HbDataStore.java

License:Open Source License

/** Sets the tuplizer */
protected void setTuplizer() {
    for (Iterator<?> pcs = getClassMappings(); pcs.hasNext();) {
        final PersistentClass pc = (PersistentClass) pcs.next();
        if (pc.getMetaAttribute(HbMapperConstants.FEATUREMAP_META) != null) { // featuremap
            // entry
            pc.addTuplizer(EntityMode.MAP,
                    getHbContext().getFeatureMapEntryTuplizer(getHibernateConfiguration()).getName());
        } else if (pc.getMetaAttribute(HbMapperConstants.ECLASS_NAME_META) != null) {
            // only the pc's with this meta should get a tuplizer

            pc.addTuplizer(EntityMode.MAP,
                    getHbContext().getEMFTuplizerClass(getHibernateConfiguration()).getName());
            pc.addTuplizer(EntityMode.POJO,
                    getHbContext().getEMFTuplizerClass(getHibernateConfiguration()).getName());
        } else if (pc.getMetaAttribute(HbMapperConstants.ECLASS_NAME_META) == null) {
            // don't change these pc's any further, these are not eclasses
            continue;
        }//from w ww.  j  a  v  a 2 s .c om

        // also set the tuplizer for the components, and register for the
        // component

        // Build a list of all properties.
        java.util.List<Property> properties = new ArrayList<Property>();
        final Property identifierProperty = pc.getIdentifierProperty();
        if (identifierProperty != null) {
            properties.add(identifierProperty);
        }
        for (Iterator<?> it = pc.getPropertyIterator(); it.hasNext();) {
            properties.add((Property) it.next());
        }

        // Now set component tuplizers where necessary.
        for (Object name2 : properties) {
            Property prop = (Property) name2;
            if (prop.getName().compareTo("_identifierMapper") == 0) {
                continue; // ignore this one
            }
            final Value value = prop.getValue();
            if (value instanceof Component) {
                setComponentTuplizer((Component) value, getHibernateConfiguration());
            } else if (value instanceof Collection && ((Collection) value).getElement() instanceof Component) {
                setComponentTuplizer((Component) ((Collection) value).getElement(),
                        getHibernateConfiguration());
            }
        }
    }
}

From source file:org.eclipse.emf.teneo.hibernate.HbDataStore.java

License:Open Source License

/**
 * Sets the emf component tuplizer (if it is an eclass) or the hibernate
 * component tuplizer//w  w  w  .j  a v  a2  s. c  o  m
 */
protected void setComponentTuplizer(Component component, Configuration cfg) {
    // check if the eclass exists
    // todo: change recognizing a component to using metadata!
    EClass eClass = ERuntime.INSTANCE.getEClass(component.getComponentClass());
    if (eClass == null) {
        eClass = getEntityNameStrategy().toEClass(component.getComponentClassName());
    }
    if (eClass != null) {
        if (log.isDebugEnabled()) {
            log.debug("Found " + eClass.getName() + " as a component");
        }
    } else {
        eClass = HbUtil.getEClassFromMeta(component);
        if (eClass == null) {
            return;
        }
    }

    // is a valid eclass
    component.addTuplizer(EntityMode.MAP, getHbContext().getEMFComponentTuplizerClass(cfg).getName());
    component.addTuplizer(EntityMode.POJO, getHbContext().getEMFComponentTuplizerClass(cfg).getName());
    HbHelper.INSTANCE.registerDataStoreByComponent(this, component);
}

From source file:org.eclipse.emf.teneo.hibernate.mapping.identifier.IdentifierUtil.java

License:Open Source License

/** Returns the id of the passed object */
@SuppressWarnings("deprecation")
public static Serializable getID(EObject eobj, HbDataStore hd) {
    final String entityName = hd.getEntityNameStrategy().toEntityName(eobj.eClass());
    final EntityPersister entityPersister = ((SessionFactoryImpl) hd.getSessionFactory())
            .getEntityPersister(entityName);
    return entityPersister.getIdentifier(eobj, EntityMode.MAP);
}