Example usage for org.hibernate.metadata ClassMetadata getIdentifierType

List of usage examples for org.hibernate.metadata ClassMetadata getIdentifierType

Introduction

In this page you can find the example usage for org.hibernate.metadata ClassMetadata getIdentifierType.

Prototype

Type getIdentifierType();

Source Link

Document

Get the identifier Hibernate type

Usage

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

License:Open Source License

/**
 * Read all the properties from Hibernate metadata
 *//*from w  w  w  . j ava 2s  .co  m*/
private void loadAllProperties() {
    if (allPropsRetrieved)
        return;

    synchronized (this) {
        if (!allPropsRetrieved) {
            metaAttributes = new HashMap<String, MetaAttribute>();
            metaRoles = new HashMap<String, MetaRole>();
            ClassMetadata meta = persister.getClassMetadata();
            String[] propNames = meta.getPropertyNames();
            for (String propName : propNames) {
                Type type;
                try {
                    type = persister.getClassMetadata().getPropertyType(propName);
                } catch (QueryException ex) {
                    throw new RuntimeException("Unable to determine type for property " + propName
                            + " of entity " + persister.getEntityName());
                }
                if (type.isComponentType()) {
                    // Do nothing
                } else if (type.isCollectionType() || type.isEntityType() || type.isAssociationType()) {
                    boolean isParentToChild = type.isCollectionType();
                    MetaRole mr = new HibMetaRole(this, propName, isParentToChild);
                    metaRoles.put(propName, mr);
                } else {
                    MetaAttribute ma = new HibMetaAttribute(propName, type.getReturnedClass(), false);
                    metaAttributes.put(propName, ma);
                }
            }

            // Often the primary attribute(s) is not returned by ClassMetadata.getPropertyNames
            // So we add it by hand here
            String pkName = meta.getIdentifierPropertyName();

            if (pkName == null) { // Can happen for composite keys
                Type pkType = meta.getIdentifierType();
                if (pkType.isComponentType()) {
                    ComponentType ctype = (ComponentType) pkType;
                    String[] pnames = ctype.getPropertyNames();
                    for (String pname : pnames) {
                        MetaAttribute ma = new HibMetaAttribute(pname,
                                meta.getPropertyType(pname).getReturnedClass(), false);
                        metaAttributes.put(pname, ma);
                    }
                } else
                    throw new RuntimeException(
                            "Unexpected: anonymous PK is not composite - class " + meta.getEntityName());
            } else if (!metaAttributes.containsKey(pkName)) {
                MetaAttribute ma = new HibMetaAttribute(pkName, meta.getIdentifierType().getReturnedClass(),
                        false);
                metaAttributes.put(pkName, ma);
            }

            allPropsRetrieved = true;
        }
    }
}

From source file:com.idega.jbpm.context.exe.matcher.HibernateLongIdMatcher.java

License:Open Source License

public boolean matches(final Object value) {

    Boolean res = getBpmContext().execute(new JbpmCallback() {

        public Object doInJbpm(JbpmContext context) throws JbpmException {
            @SuppressWarnings("unchecked")
            Class valueClass = value.getClass();
            if (value instanceof HibernateProxy) {
                valueClass = valueClass.getSuperclass();
            }// ww w. j  a  va  2  s. c o m

            boolean matches = false;

            SessionFactory sessionFactory = context.getSession().getSessionFactory();

            if (sessionFactory != null) {
                ClassMetadata classMetadata = sessionFactory.getClassMetadata(valueClass);
                matches = ((classMetadata != null)
                        && (classMetadata.getIdentifierType().getClass() == LongType.class));
            }
            return matches;
        }
    });

    return res;
}

From source file:com.idega.jbpm.context.exe.matcher.HibernateStringIdMatcher.java

License:Open Source License

public boolean matches(final Object value) {

    Boolean res = getBpmContext().execute(new JbpmCallback() {

        public Object doInJbpm(JbpmContext context) throws JbpmException {
            @SuppressWarnings("unchecked")
            Class valueClass = value.getClass();
            if (value instanceof HibernateProxy) {
                valueClass = valueClass.getSuperclass();
            }/*from  w ww  .ja  v a  2  s. c om*/

            boolean matches = false;

            SessionFactory sessionFactory = context.getSession().getSessionFactory();

            if (sessionFactory != null) {
                ClassMetadata classMetadata = sessionFactory.getClassMetadata(valueClass);
                matches = ((classMetadata != null)
                        && (classMetadata.getIdentifierType().getClass() == StringType.class));
            }
            return matches;
        }
    });

    return res;
}

From source file:com.klistret.cmdb.utility.hibernate.XPathCriteria.java

License:Open Source License

/**
 * Get Hibernate property type by looking for the property name in the class
 * metadata for general properties and the identifier property
 * /*from  w ww  . j  a  v a  2 s .  c o m*/
 * @param cm
 * @param name
 * @return
 */
private org.hibernate.type.Type getPropertyType(ClassMetadata cm, String name) {

    for (String pn : cm.getPropertyNames())
        if (pn.equals(name))
            return cm.getPropertyType(name);

    if (cm.getIdentifierPropertyName() != null && cm.getIdentifierPropertyName().equals(name))
        return cm.getIdentifierType();

    return null;
}

From source file:com.mg.framework.support.report.ReportUtils.java

License:Open Source License

/**
 *   BIRT    BAi, ..  BIRT   , //from w w w.j  av a 2 s  .c  o m
 * ? ?? ??  ? ?      ,
 *    ?     ? custom  ??. ? 
 *  ??  Entity.  ??  ? ? 
 * {@link com.mg.framework.api.report.RptProperties#ENTITY_IDS_DATASET_PARAMETER}  {@link
 * com.mg.framework.api.report.RptProperties#BUSINESS_SERVICE_DATASET_PARAMETER}
 *
 * @param name          ? 
 * @param value            
 * @param entityManager   ??
 * @return   
 */
public static Object convertParamValue(String name, Object value, Object entityManager) {
    if (value instanceof String) {
        String strValue = (String) value;
        if (RptProperties.ENTITY_IDS_DATASET_PARAMETER.equalsIgnoreCase(name)) {
            //{<java type>#<identificator value>}[,{<java type>#<identificator value>}]
            if (strValue.startsWith("{") && strValue.endsWith("}")) {
                String[] strIds = StringUtils.split(strValue.substring(1, strValue.length() - 1), "},{")
                        .toArray(new String[0]);
                int length = strIds.length;
                if (length == 0)
                    return value;
                // ?? ?   > 1,  ? ? 
                //   ? ??? ?   QL ?
                if (length > 1) {
                    Serializable[] ids = new Serializable[strIds.length];
                    for (int i = 0; i < strIds.length; i++)
                        ids[i] = convertStringToID(strIds[i]);
                    return ids;
                } else
                    return convertStringToID(strIds[0]);
            } else
                return value;
        } else if (RptProperties.BUSINESS_SERVICE_DATASET_PARAMETER.equalsIgnoreCase(name)) {
            //? ?? ?-
            return ApplicationDictionaryLocator.locate().getBusinessService(strValue);
        } else if (strValue.startsWith("${entity:") && strValue.endsWith("}")) {
            //? ? ?? ??,   ??
            //${entity:<entity name>#<identificator value>[;searchHelp:<search help name>]}
            if (logger != null)
                logger.debug("convert entity parameter: " + strValue);
            strValue = strValue.substring(9, strValue.length() - 1);
            //   searchHelp
            int idx = strValue.indexOf(";searchHelp:");
            if (idx != -1)
                strValue = strValue.substring(0, idx);
            String[] entityInfo = strValue.split("#");
            //???  ? ?  ??
            if (entityInfo.length != 2) {
                if (logger != null)
                    logger.error("invalid entity description: " + strValue);
                return null;
            }
            Session entityManagerImpl = (Session) entityManager;
            ClassMetadata classMetadata = entityManagerImpl.getSessionFactory().getClassMetadata(entityInfo[0]);
            if (classMetadata == null) {
                logger.error("metadata of entity not found: " + entityInfo[0]);
                return null;
            }
            Type type = classMetadata.getIdentifierType();
            Serializable entityID = entityInfo[1];
            if (type instanceof IntegerType)
                entityID = Integer.parseInt((String) entityID);
            if (type instanceof LongType)
                entityID = Long.parseLong((String) entityID);
            return entityManagerImpl.get(entityInfo[0], entityID);
        } else
            return value;
    } else
        return value;
}

From source file:com.mg.merp.report.parameters.support.ReportParameterImpl.java

License:Open Source License

private DataType handleStringType(IScalarParameterDefn param) {
    if (param.getDataType() != IScalarParameterDefn.TYPE_STRING)
        throw new IllegalArgumentException("Parameter type is not string");

    String defValue = param.getDefaultValue();
    if (defValue != null && defValue.startsWith("${entity:") && defValue.endsWith("}")) {
        //${entity:<entity name>[#<identificator value>][;searchHelp:<search help name>]}
        List<String> descs = StringUtils.split(defValue.substring(2, defValue.length() - 1), ";");
        for (String desc : descs) {
            if (desc.startsWith("entity:")) {
                //set entity
                String entityDesc = desc.substring(7);
                String entityName;
                int valueIdx = entityDesc.indexOf("#");
                if (valueIdx != -1) {
                    //? 
                    entityName = entityDesc.substring(0, valueIdx);
                    ClassMetadata classMetadata = ((Session) ServerUtils.getPersistentManager().getDelegate())
                            .getSessionFactory().getClassMetadata(entityName);
                    if (classMetadata == null)
                        throw new IllegalArgumentException("Metadata of entity not found: " + entityName);
                    Type type = classMetadata.getIdentifierType();
                    Object entityID = entityDesc.substring(valueIdx + 1, entityDesc.length());
                    if (type instanceof IntegerType)
                        entityID = Integer.parseInt((String) entityID);
                    if (type instanceof LongType)
                        entityID = Long.parseLong((String) entityID);
                    this.value = ServerUtils.getPersistentManager().find(entityName, entityID);
                } else {
                    entityName = entityDesc;
                    this.value = null;
                }//from w w w . ja  va 2  s .c  o  m

                DataItem dataItem = getFieldDataItem(entityName);
                if (dataItem != null) {
                    entityPropertyText = dataItem.getEntityPropertyText();
                    entityPropertyTextFormat = dataItem.getEntityTextFormat();
                    // ?  ?,  ?? ?  ?? ??
                    if (searchHelpName == null)
                        searchHelpName = dataItem.getSearchHelpName();
                }
            } else if (desc.startsWith("searchHelp:")) {
                //set search help
                String searchHelpName = desc.substring(11);
                this.searchHelpName = searchHelpName;
            }
        }
        return ReportParameter.DataType.ENTITY;
    } else
        return ReportParameter.DataType.STRING;
}

From source file:com.supermy.base.service.WebMetaService.java

License:Apache License

/**
 *
 *
 * @param domainName/*from w  w  w. j  a  v  a2 s.  c om*/
 * @return
  */
public Map getHibernateMetaJson(String domainName) {
    System.out.println("getHibernateMetaJson:" + domainName);

    ClassMetadata meta = sessionfactory.getClassMetadata(domainName);

    //Object[] propertyValues = catMeta.getPropertyValues(fritz);
    String[] propertyNames = meta.getPropertyNames();
    Type[] propertyTypes = meta.getPropertyTypes();

    // get a Map of all properties which are not collections or associations
    Map namedValues = new HashMap();
    for (int i = 0; i < propertyNames.length; i++) {
        namedValues.put(propertyNames[i], propertyTypes[i].getName());
        //         if ( !propertyTypes[i].isEntityType() && !propertyTypes[i].isCollectionType() ) {
        //            namedValues.put( propertyNames[i], propertyValues[i] );
        //         }
    }
    //configuration.getClassMapping([entity class name]).getTable().getColumn([column number]).getComment()

    Map result = new HashMap();
    result.put("domainName", meta.getEntityName());
    result.put("entityName", meta.getMappedClass().getSimpleName());
    result.put("id", meta.getIdentifierPropertyName());
    result.put("idType", meta.getIdentifierType().getName());

    result.put("data", namedValues);

    System.out.println(result);

    return result;
}

From source file:cz.jirutka.rsql.hibernate.builder.IdentifierCriterionBuilder.java

License:Open Source License

@Override
public Criterion createCriterion(String property, Comparison operator, String argument, Class<?> entityClass,
        String alias, CriteriaBuilder builder) throws ArgumentFormatException, UnknownSelectorException {

    Class<?> type = findPropertyType(property, builder.getClassMetadata(entityClass));
    ClassMetadata assocClassMetadata = builder.getClassMetadata(type);
    Class<?> idType = assocClassMetadata.getIdentifierType().getReturnedClass();

    LOG.debug("Property is association type {}, parsing argument to ID type {}", type, idType.getSimpleName());

    Object parsedArgument = builder.getArgumentParser().parse(argument, idType);
    String propertyPath = alias + property + ".id";

    return createCriterion(propertyPath, operator, parsedArgument);
}

From source file:edu.utah.further.core.data.util.HibernateUtil.java

License:Apache License

/**
 * Generates an SQL in (...) statement to be used with in statements involving
 * composite keys./* w  ww .  j  a  v  a 2s .  c  om*/
 *
 * This method is strictly a workaround utility method for an issue with using
 * {@link Restrictions#in(String, java.util.Collection)} with a composite key. It
 * generates an sql statement correctly but binds the parameters wrong. This issue has
 * been reported SEVERAL times, as early as 05 and it still hasn't been fixed (it's
 * 09). There is a 2 second correction that needs to be added to the code to fix the
 * issue but for some reason Hibernate developers refuse to do it. In light of not
 * knowing what else it might break in custom compiling Hibernate with the fix it was
 * preferred to do a work around. It is to be used directly with
 * {@link Restrictions#sqlRestriction(String)}.
 *
 * @param entityClass
 *            the entity which contains the composite key for which an SQL in
 *            statement needs to be generated
 * @param sessionFactory
 *            the {@link SessionFactory} assosciated with the entities
 * @param elementsSize
 *            the size of the elements that will be in the in clause
 * @return
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-708
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-1575
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-1743
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-1832
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-1972
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-3164
 */
public static String sqlRestrictionCompositeIn(final Class<? extends PersistentEntity<?>> entityClass,
        final SessionFactory sessionFactory, final int elementsSize) {
    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
    final String identifierName = classMetadata.getIdentifierPropertyName();
    final Type identifierType = classMetadata.getIdentifierType();

    if (!(identifierType.isComponentType())) {
        return Strings.EMPTY_STRING;
    }

    final ComponentType componentType = (ComponentType) identifierType;
    final String[] idPropertyNames = componentType.getPropertyNames();

    final PropertyMapping propertyMapping = getPropertyMapping(entityClass, sessionFactory);

    final StringBuilder inString = StringUtil.newStringBuilder();

    // field names -- ({alias}.field1, {alias}.field2)
    inString.append('(');
    for (int i = 0; i < idPropertyNames.length; i++) {
        inString.append("{alias}").append('.')
                // Look up the database field from the property path
                .append(propertyMapping.toColumns(identifierName + "." + idPropertyNames[i])[0]);
        if (i + 1 < idPropertyNames.length) {
            inString.append(", ");
        } else {
            inString.append(')');
        }
    }

    // values -- in ( (?, ?), (?, ?) )
    inString.append(" in ").append('(');
    for (int i = 0; i < elementsSize; i++) {
        if (elementsSize % MAX_IN == 0) {
            inString.append(')');
            inString.append(Strings.EMPTY_STRING);
            inString.append("or");
            inString.append(Strings.EMPTY_STRING);
            inString.append('(');
        }

        inString.append('(');
        for (int j = 0; j < idPropertyNames.length; j++) {
            inString.append('?');
            if (j + 1 < idPropertyNames.length) {
                inString.append(",");
            }
        }
        inString.append(')');
        if ((i + 1 < elementsSize) && (i + 1 % MAX_IN != 0)) {
            inString.append(", ");
        }
    }
    inString.append(')');

    return inString.toString();
}

From source file:edu.utah.further.ds.impl.executor.db.hibernate.criteria.HibernateCountSearchQueryExecutor.java

License:Apache License

@SuppressWarnings("boxing")
@Override/*from  w w  w. ja v  a2  s . c  o  m*/
public boolean process(final ChainRequest request) {
    final HibernateExecReq execReq = new HibernateExecReq(request);
    final GenericCriteria criteria = execReq.getResult();
    notNull(criteria, "Expected Hibernate criteria");

    final Class<? extends PersistentEntity<?>> domainClass = execReq.getRootEntity();

    final SessionFactory sessionFactory = execReq.getSessionFactory();
    notNull(sessionFactory, "Expected SessionFactory");

    // Get information about the root entity class
    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(domainClass);
    final String identifierName = classMetadata.getIdentifierPropertyName();
    final Type identifierType = classMetadata.getIdentifierType();

    if (identifierType.isComponentType()) {
        criteria.setProjection(Projections.countDistinct(identifierName + "." + identifierName));
    } else {
        criteria.setProjection(Projections.countDistinct(identifierName));
    }
    Long result = -1l;
    try {
        result = criteria.uniqueResult();
    } catch (final HibernateException e) {
        if (log.isDebugEnabled()) {
            log.debug("Caught Hibernate exception.");
        }
    }

    execReq.setResult(result);
    execReq.setStatus("Returned search query count result");

    return false;
}