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:gr.interamerican.bo2.impl.open.hibernate.HibernateConfigurations.java

License:Open Source License

/**
 * Creates a SessionFactory./*  ww w.  ja  v a2 s .  com*/
 * 
 * @param pathToCfg
 *        Path to the hibernate configuration file.
 * @param dbSchema
 *        Db schema.
 * @param sessionInterceptor
 *        Hibernate session interceptor.
 * @param hibernateMappingsPath
 *        Path to file that lists files indexing hbm files this session factory
 *        should be configured with
 * 
 * @return Returns the session factory.
 * 
 * @throws InitializationException
 *         If the creation of the SessionFactory fails.
 */
@SuppressWarnings("nls")
static SessionFactory createSessionFactory(String pathToCfg, String dbSchema, String sessionInterceptor,
        String hibernateMappingsPath) throws InitializationException {
    try {
        Configuration conf = new Configuration();

        Interceptor interceptor = getInterceptor(sessionInterceptor);
        if (interceptor != null) {
            conf.setInterceptor(interceptor);
        }

        conf.setProperty(SCHEMA_PROPERTY, dbSchema);

        List<String> hbms = getHibernateMappingsIfAvailable(hibernateMappingsPath);
        for (String entityMapping : hbms) {
            LOGGER.debug("Adding " + entityMapping + " to the session factory configuration.");
            conf.addResource(entityMapping);
        }

        conf.configure(pathToCfg);

        conf.getEntityTuplizerFactory().registerDefaultTuplizerClass(EntityMode.POJO,
                Bo2PojoEntityTuplizer.class);
        SessionFactory sessionFactory = conf.buildSessionFactory();
        ((SessionFactoryImpl) sessionFactory).registerEntityNameResolver(Bo2EntityNameResolver.INSTANCE,
                EntityMode.POJO);
        sessionFactory.getStatistics().setStatisticsEnabled(true);
        return sessionFactory;
    } catch (HibernateException e) {
        throw new InitializationException(e);
    }
}

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override//from  w  ww.  jav a2 s .  c  o m
public Object invokeMethod(String name, Object obj) {
    Object[] args = obj.getClass().isArray() ? (Object[]) obj : new Object[] { obj };

    if (paginationEnabledList && SET_RESULT_TRANSFORMER_CALL.equals(name) && args.length == 1
            && args[0] instanceof ResultTransformer) {
        resultTransformer = (ResultTransformer) args[0];
        return null;
    }

    if (isCriteriaConstructionMethod(name, args)) {
        if (criteria != null) {
            throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here"));
        }

        if (name.equals(GET_CALL)) {
            uniqueResult = true;
        } else if (name.equals(SCROLL_CALL)) {
            scroll = true;
        } else if (name.equals(COUNT_CALL)) {
            count = true;
        } else if (name.equals(LIST_DISTINCT_CALL)) {
            resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
        }

        createCriteriaInstance();

        // Check for pagination params
        if (name.equals(LIST_CALL) && args.length == 2) {
            paginationEnabledList = true;
            orderEntries = new ArrayList<Order>();
            invokeClosureNode(args[1]);
        } else {
            invokeClosureNode(args[0]);
        }

        if (resultTransformer != null) {
            criteria.setResultTransformer(resultTransformer);
        }
        Object result;
        if (!uniqueResult) {
            if (scroll) {
                result = criteria.scroll();
            } else if (count) {
                criteria.setProjection(Projections.rowCount());
                result = criteria.uniqueResult();
            } else if (paginationEnabledList) {
                // Calculate how many results there are in total. This has been
                // moved to before the 'list()' invocation to avoid any "ORDER
                // BY" clause added by 'populateArgumentsForCriteria()', otherwise
                // an exception is thrown for non-string sort fields (GRAILS-2690).
                criteria.setFirstResult(0);
                criteria.setMaxResults(Integer.MAX_VALUE);
                criteria.setProjection(Projections.rowCount());
                int totalCount = ((Number) criteria.uniqueResult()).intValue();

                // Restore the previous projection, add settings for the pagination parameters,
                // and then execute the query.
                if (projectionList != null && projectionList.getLength() > 0) {
                    criteria.setProjection(projectionList);
                } else {
                    criteria.setProjection(null);
                }
                for (Order orderEntry : orderEntries) {
                    criteria.addOrder(orderEntry);
                }
                if (resultTransformer == null) {
                    criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
                } else if (paginationEnabledList) {
                    // relevant to GRAILS-5692
                    criteria.setResultTransformer(resultTransformer);
                }
                // GRAILS-7324 look if we already have association to sort by
                Map argMap = (Map) args[0];
                final String sort = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_SORT);
                if (sort != null) {
                    boolean ignoreCase = true;
                    Object caseArg = argMap.get(GrailsHibernateUtil.ARGUMENT_IGNORE_CASE);
                    if (caseArg instanceof Boolean) {
                        ignoreCase = (Boolean) caseArg;
                    }
                    final String orderParam = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_ORDER);
                    final String order = GrailsHibernateUtil.ORDER_DESC.equalsIgnoreCase(orderParam)
                            ? GrailsHibernateUtil.ORDER_DESC
                            : GrailsHibernateUtil.ORDER_ASC;
                    int lastPropertyPos = sort.lastIndexOf('.');
                    String associationForOrdering = lastPropertyPos >= 0 ? sort.substring(0, lastPropertyPos)
                            : null;
                    if (associationForOrdering != null && aliasMap.containsKey(associationForOrdering)) {
                        addOrder(criteria, aliasMap.get(associationForOrdering) + "."
                                + sort.substring(lastPropertyPos + 1), order, ignoreCase);
                        // remove sort from arguments map to exclude from default processing.
                        @SuppressWarnings("unchecked")
                        Map argMap2 = new HashMap(argMap);
                        argMap2.remove(GrailsHibernateUtil.ARGUMENT_SORT);
                        argMap = argMap2;
                    }
                }
                GrailsHibernateUtil.populateArgumentsForCriteria(grailsApplication, targetClass, criteria,
                        argMap);
                PagedResultList pagedRes = new PagedResultList(criteria.list());

                // Updated the paged results with the total number of records calculated previously.
                pagedRes.setTotalCount(totalCount);
                result = pagedRes;
            } else {
                result = criteria.list();
            }
        } else {
            result = GrailsHibernateUtil.unwrapIfProxy(criteria.uniqueResult());
        }
        if (!participate) {
            hibernateSession.close();
        }
        return result;
    }

    if (criteria == null)
        createCriteriaInstance();

    MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
    if (metaMethod != null) {
        return metaMethod.invoke(this, args);
    }

    metaMethod = criteriaMetaClass.getMetaMethod(name, args);
    if (metaMethod != null) {
        return metaMethod.invoke(criteria, args);
    }
    metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
    if (metaMethod != null) {
        return metaMethod.invoke(criteria, args);
    }

    if (isAssociationQueryMethod(args) || isAssociationQueryWithJoinSpecificationMethod(args)) {
        final boolean hasMoreThanOneArg = args.length > 1;
        Object callable = hasMoreThanOneArg ? args[1] : args[0];
        int joinType = hasMoreThanOneArg ? (Integer) args[0] : CriteriaSpecification.INNER_JOIN;

        if (name.equals(AND) || name.equals(OR) || name.equals(NOT)) {
            if (criteria == null) {
                throwRuntimeException(
                        new IllegalArgumentException("call to [" + name + "] not supported here"));
            }

            logicalExpressionStack.add(new LogicalExpression(name));
            invokeClosureNode(callable);

            LogicalExpression logicalExpression = logicalExpressionStack
                    .remove(logicalExpressionStack.size() - 1);
            addToCriteria(logicalExpression.toCriterion());

            return name;
        }

        if (name.equals(PROJECTIONS) && args.length == 1 && (args[0] instanceof Closure)) {
            if (criteria == null) {
                throwRuntimeException(
                        new IllegalArgumentException("call to [" + name + "] not supported here"));
            }

            projectionList = Projections.projectionList();
            invokeClosureNode(callable);

            if (projectionList != null && projectionList.getLength() > 0) {
                criteria.setProjection(projectionList);
            }

            return name;
        }

        final PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(targetClass, name);
        if (pd != null && pd.getReadMethod() != null) {
            ClassMetadata meta = sessionFactory.getClassMetadata(targetClass);
            Type type = meta.getPropertyType(name);
            if (type.isAssociationType()) {
                String otherSideEntityName = ((AssociationType) type)
                        .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
                Class oldTargetClass = targetClass;
                targetClass = sessionFactory.getClassMetadata(otherSideEntityName)
                        .getMappedClass(EntityMode.POJO);
                if (targetClass.equals(oldTargetClass) && !hasMoreThanOneArg) {
                    joinType = CriteriaSpecification.LEFT_JOIN; // default to left join if joining on the same table
                }
                associationStack.add(name);
                final String associationPath = getAssociationPath();
                createAliasIfNeccessary(name, associationPath, joinType);
                // the criteria within an association node are grouped with an implicit AND
                logicalExpressionStack.add(new LogicalExpression(AND));
                invokeClosureNode(callable);
                aliasStack.remove(aliasStack.size() - 1);
                if (!aliasInstanceStack.isEmpty()) {
                    aliasInstanceStack.remove(aliasInstanceStack.size() - 1);
                }
                LogicalExpression logicalExpression = logicalExpressionStack
                        .remove(logicalExpressionStack.size() - 1);
                if (!logicalExpression.args.isEmpty()) {
                    addToCriteria(logicalExpression.toCriterion());
                }
                associationStack.remove(associationStack.size() - 1);
                targetClass = oldTargetClass;

                return name;
            }
        }
    } else if (args.length == 1 && args[0] != null) {
        if (criteria == null) {
            throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here"));
        }

        Object value = args[0];
        Criterion c = null;
        if (name.equals(ID_EQUALS)) {
            return eq("id", value);
        }

        if (name.equals(IS_NULL) || name.equals(IS_NOT_NULL) || name.equals(IS_EMPTY)
                || name.equals(IS_NOT_EMPTY)) {
            if (!(value instanceof String)) {
                throwRuntimeException(new IllegalArgumentException(
                        "call to [" + name + "] with value [" + value + "] requires a String value."));
            }
            String propertyName = calculatePropertyName((String) value);
            if (name.equals(IS_NULL)) {
                c = Restrictions.isNull(propertyName);
            } else if (name.equals(IS_NOT_NULL)) {
                c = Restrictions.isNotNull(propertyName);
            } else if (name.equals(IS_EMPTY)) {
                c = Restrictions.isEmpty(propertyName);
            } else if (name.equals(IS_NOT_EMPTY)) {
                c = Restrictions.isNotEmpty(propertyName);
            }
        }

        if (c != null) {
            return addToCriteria(c);
        }
    }

    throw new MissingMethodException(name, getClass(), args);
}

From source file:joecohen.hibernatebrowser.HibernateBrowserGUI.java

License:Open Source License

public RootNode(String name, Session session, HibernateUtil util) {
    this.name = name;

    for (ClassMetadata meta : util.getMappedClasses()) {
        Class clazz = meta.getMappedClass(EntityMode.POJO);
        this.classList.add(new ClassNode(clazz, session));
    }/*w  ww.  j  a  v  a 2  s . c  o m*/

    List<ClassNode> tempClassList = new ArrayList<ClassNode>(this.classList);

    for (ClassNode cno : tempClassList) {
        for (ClassNode cni : tempClassList) {
            if (cno.clazz.getSuperclass().equals(cni.clazz)) {
                cni.classList.add(cno);
                this.classList.remove(cno);
            }
        }

    }

}

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  ww w .  ja va 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:nl.strohalm.cyclos.utils.hibernate.HibernateQueryHandler.java

License:Open Source License

/**
 * Copies the persistent properties from the source to the destination entity
 *//*from  ww  w. j a v a2s.c om*/
public void copyProperties(final Entity source, final Entity dest) {
    if (source == null || dest == null) {
        return;
    }
    final ClassMetadata metaData = getClassMetaData(source);
    final Object[] values = metaData.getPropertyValues(source, EntityMode.POJO);
    // Skip the collections
    final Type[] types = metaData.getPropertyTypes();
    for (int i = 0; i < types.length; i++) {
        final Type type = types[i];
        if (type instanceof CollectionType) {
            values[i] = null;
        }
    }
    metaData.setPropertyValues(dest, values, EntityMode.POJO);
}

From source file:ome.services.search.SearchAction.java

License:Open Source License

private TypedValue fixDiscriminatorTypeValue(TypedValue typedValue) {
    Object value = typedValue.getValue();

    // check to make sure we can reconstruct an equivalent TypedValue
    if (!String.class.isInstance(value) || !typedValue
            .equals(new TypedValue(typedValue.getType(), typedValue.getValue(), EntityMode.POJO))) {
        return typedValue;
    }/*from www  . j a va 2 s .  c o m*/

    //
    // If begins and ends with a quote,
    // then replace leading and trailing apostrophes,
    // otherwise return
    //
    String svalue = value.toString();
    if (svalue.charAt(0) == '\'' && svalue.charAt(svalue.length() - 1) == '\'') {
        value = svalue.substring(1, svalue.length() - 1);
        return new TypedValue(typedValue.getType(), value, EntityMode.POJO);
    } else {
        return typedValue;
    }
}

From source file:org.apache.click.extras.hibernate.HibernateForm.java

License:Apache License

/**
 * Set the given Hibernate value object in the form, copying the object's
 * properties into the form field values.
 *
 * @param valueObject the Hibernate value object to set
 *///from ww  w. ja va 2s  . c o  m
public void setValueObject(Object valueObject) {
    if (valueObject != null) {

        String classname = getClassname(valueObject.getClass());

        ClassMetadata classMetadata = getSessionFactory().getClassMetadata(classname);

        Object identifier = classMetadata.getIdentifier(valueObject, EntityMode.POJO);
        oidField.setValueObject(identifier);

        copyFrom(valueObject);
    }
}

From source file:org.atemsource.atem.impl.hibernate.HibernateEntityType.java

License:Apache License

@Override
public Class<Object> getJavaType() {
    if (classMetadata == null) {
        return getEntityClass();
    } else {//from  w  ww  .java  2s.  c  o  m
        return classMetadata.getMappedClass(EntityMode.POJO);
    }
}

From source file:org.atemsource.atem.impl.hibernate.HibernateMetaDataRepository.java

License:Apache License

private HibernateEntityType createEntityType(final ClassMetadata classMetadata) {
    Type identifierType = classMetadata.getIdentifierType();
    HibernateEntityType entityType = null;
    entityType = beanCreator.create(HibernateEntityType.class);
    entityType.setPrimaryKeyNullable(!identifierType.getReturnedClass().isPrimitive());
    entityType.setEntityClass(classMetadata.getMappedClass(EntityMode.POJO));
    attacheServicesToEntityType(entityType);
    return entityType;
}

From source file:org.atemsource.atem.impl.hibernate.HibernateMetaDataRepository.java

License:Apache License

public void init() {

    Map classMetadataMap = sessionFactory.getAllClassMetadata();
    // initialize entity types.
    for (Object entry : classMetadataMap.entrySet()) {
        String entityName = (String) ((Map.Entry) entry).getKey();
        ClassMetadata classMetadata = (ClassMetadata) ((Map.Entry) entry).getValue();
        if (entityTypeCreationContext.hasEntityTypeReference(classMetadata.getMappedClass(EntityMode.POJO))) {
            continue;
        }//from   w  w  w.  jav a 2 s .co  m
        HibernateEntityType entityType = createEntityType(classMetadata);
        entityType.setEntityClass(classMetadata.getMappedClass(EntityMode.POJO));
        entityType.setCode(entityName);
        nameToEntityTypes.put(entityName, entityType);
        entityType.setClassMetadata(classMetadata);
    }

    // initialize type hierachy.
    for (Object entry : classMetadataMap.entrySet()) {
        ClassMetadata classMetadata = (ClassMetadata) ((Map.Entry) entry).getValue();
        if (entityTypeCreationContext.hasEntityTypeReference(classMetadata.getMappedClass(EntityMode.POJO))) {
            continue;
        }
        String entityName = (String) ((Map.Entry) entry).getKey();
        AbstractEntityType entityType = nameToEntityTypes.get(entityName);
        Class mappedClass = classMetadata.getMappedClass(EntityMode.POJO);
        Class superClass = mappedClass.getSuperclass();
        ClassMetadata superClassMetadata = sessionFactory.getClassMetadata(superClass);
        if (superClassMetadata != null) {
            String superTypeCode = superClassMetadata.getEntityName();
            initializeEntityTypeHierachy(entityType, superTypeCode);
        } else {
            EntityType superEntityType = createSuperEntityType(superClass);
            if (superEntityType != null) {
                initializeEntityTypeHierachy(entityType, superEntityType.getCode());
            }
        }
    }

    // initialize mapped superclasses.
    initializedMappedSuperClass = new HashSet<String>();
    for (Object entry : classMetadataMap.entrySet()) {
        String entityName = (String) ((Map.Entry) entry).getKey();
        ClassMetadata classMetadata = (ClassMetadata) ((Map.Entry) entry).getValue();
        if (entityTypeCreationContext.hasEntityTypeReference(classMetadata.getMappedClass(EntityMode.POJO))) {
            continue;
        }
        AbstractEntityType entityType = nameToEntityTypes.get(entityName);
        MetaLogs.LOG.debug("Initializing properties of " + entityName + "");
        Set<Attribute> attributes = createAttributes(classMetadata, entityType);
        initializeHibernateSuperEntityType(entityType, classMetadata);
        entityType.setAttributes(new ArrayList(attributes));
    }

    // intialize lookups
    initializeLookups();
    if (failIfPropertyNotMappable && fieldWasNotMapped) {
        throw new IllegalStateException("some fields were not mapped");
    }
}