Java Code Examples for org.hibernate.metadata.ClassMetadata.getIdentifier()

The following are Jave code examples for showing how to use getIdentifier() of the org.hibernate.metadata.ClassMetadata class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: UniqueValidator   File: UniqueValidator.java   View Source Code Vote up 6 votes
private TreeMap<String, Object> _countRows(Object value) {
    ClassMetadata meta = getSessionFactory().getClassMetadata(value.getClass());
    String idName = meta.getIdentifierPropertyName();
    Serializable idValue = meta.getIdentifier(value, (SessionImplementor)getTmpSession());

    ArrayList<String[]> fieldSets;
    if(this._fields.length > 0){
        fieldSets = _prepareFields();
    }else{
        fieldSets = _getFieldsFromUniqueConstraint(value);
        fieldSets.addAll(_extractFieldsFromObject(value));
    }

    for(String[] fieldSet : fieldSets){
        TreeMap<String, Object> fieldMap = new TreeMap<>();
        for(String fieldName: fieldSet){
            fieldMap.put(fieldName, meta.getPropertyValue(value, fieldName));
        }
        if(_hasRecord(value, fieldMap, idName, idValue, meta)){
            return fieldMap;
        }
    }

    return null;
}
 
Example 2
Project: xap-openspaces   File: CriteriaHibernateExternalDataSource.java   View Source Code Vote up 6 votes
/**
 * Return pojo identifier
 */
protected Object getId(Object template) {
    Object id = null;

    ClassMetadata classMetaData = getMetadata(template);

    if (classMetaData == null) //Unexpected class entity
        return null;

    if (template instanceof IGSEntry) {
        id = ((IGSEntry) template).getFieldValue(classMetaData.getIdentifierPropertyName());
    } else {
        id = classMetaData.getIdentifier(template);
    }

    return id;
}
 
Example 3
Project: breeze.server.java   File: RelationshipFixer.java   View Source Code Vote up 6 votes
/**
 * Get the value of the foreign key property.  This comes from the entity, but if that value is
 * null, and the entity is deleted, we try to get it from the originalValuesMap.
 * @param entityInfo Breeze EntityInfo
 * @param meta Metadata for the entity class
 * @param foreignKeyName Name of the foreign key property of the entity, e.g. "CustomerID"
 * @return
 */
private Object getForeignKeyValue(EntityInfo entityInfo, ClassMetadata meta, String foreignKeyName) {
    Object entity = entityInfo.entity;
    Object id = null;
    if (foreignKeyName.equalsIgnoreCase(meta.getIdentifierPropertyName())) {
        id = meta.getIdentifier(entity, null);
    } else if (Arrays.asList(meta.getPropertyNames()).contains(foreignKeyName)) {
        id = meta.getPropertyValue(entity, foreignKeyName);
    } else if (meta.getIdentifierType().isComponentType()) {
        // compound key
        ComponentType compType = (ComponentType) meta.getIdentifierType();
        int index = Arrays.asList(compType.getPropertyNames()).indexOf(foreignKeyName);
        if (index >= 0) {
            Object idComp = meta.getIdentifier(entity, null);
            id = compType.getPropertyValue(idComp, index, EntityMode.POJO);
        }
    }

    if (id == null && entityInfo.entityState == EntityState.Deleted) {
        id = entityInfo.originalValuesMap.get(foreignKeyName);
    }
    return id;
}
 
Example 4
Project: spacewalk   File: HibernateFactory.java   View Source Code Vote up 6 votes
/**
 * Util to reload an object using Hibernate
 * @param obj to be reloaded
 * @return Object found if not, null
 * @throws HibernateException if something bad happens.
 */
public static Object reload(Object obj) throws HibernateException {
    // assertNotNull(obj);
    ClassMetadata cmd = connectionManager.getMetadata(obj);
    Serializable id = cmd.getIdentifier(obj, EntityMode.POJO);
    Session session = getSession();
    session.flush();
    session.evict(obj);
    /*
     * In hibernate 3, the following doesn't work:
     * session.load(obj.getClass(), id);
     * load returns the proxy class instead of the persisted class, ie,
     * Filter$$EnhancerByCGLIB$$9bcc734d_2 instead of Filter.
     * session.get is set to not return the proxy class, so that is what we'll use.
     */
    // assertNotSame(obj, result);
    return session.get(obj.getClass(), id);
}
 
Example 5
Project: helium   File: EntityManagerFactoryImpl.java   View Source Code Vote up 5 votes
public Object getIdentifier(Object entity) {
	final Class entityClass = Hibernate.getClass( entity );
	final ClassMetadata classMetadata = emf.getSessionFactory().getClassMetadata( entityClass );
	if (classMetadata == null) {
		throw new IllegalArgumentException( entityClass + " is not an entity" );
	}
	//TODO does that work for @IdClass?
	return classMetadata.getIdentifier( entity, EntityMode.POJO );
}
 
Example 6
Project: apple-orm   File: HibernateBaseDAO2.java   View Source Code Vote up 5 votes
/**
 * 将更新对象拷贝至实体对象,并处理many-to-one的更新。
 * 
 * @param updater
 * @param po
 */
@SuppressWarnings({ "unchecked", "deprecation", "rawtypes" })
private void updaterCopyToPersistentObject(Updater updater, Object po) {
	Map map = BeanUtility.describe(updater.getBean());
	Set<Map.Entry<String, Object>> set = map.entrySet();
	for (Map.Entry<String, Object> entry : set) {
		String name = entry.getKey();
		Object value = entry.getValue();
		if (!updater.isUpdate(name, value)) {
			continue;
		}
		if (value != null) {
			Class<?> valueClass = value.getClass();
			ClassMetadata cm = getCmd(valueClass);
			if (cm != null) {
				Serializable vid = cm.getIdentifier(value);
				// 如果更新的many to one的对象的id为空,则将many to one设置为null。
				if (vid != null) {
					value = getSession().load(valueClass, vid);
				} else {
					value = null;
				}
			}
		}
		try {
			PropertyUtils.setProperty(po, name, value);
		} catch (Exception e) {
			// never
			logger.warn("更新对象时,拷贝属性异常", e);
		}
	}
}
 
Example 7
Project: apple-orm   File: HibernateBaseDAO.java   View Source Code Vote up 5 votes
/**
 * 将更新对象拷贝至实体对象,并处理many-to-one的更新。
 * 
 * @param updater
 * @param po
 */
@SuppressWarnings({ "unchecked", "deprecation", "rawtypes" })
private void updaterCopyToPersistentObject(Updater updater, Object po) {
	Map map = BeanUtility.describe(updater.getBean());
	Set<Map.Entry<String, Object>> set = map.entrySet();
	for (Map.Entry<String, Object> entry : set) {
		String name = entry.getKey();
		Object value = entry.getValue();
		if (!updater.isUpdate(name, value)) {
			continue;
		}
		if (value != null) {
			Class<?> valueClass = value.getClass();
			ClassMetadata cm = getCmd(valueClass);
			if (cm != null) {
				Serializable vid = cm.getIdentifier(value);
				// 如果更新的many to one的对象的id为空,则将many to one设置为null。
				if (vid != null) {
					value = getSession().load(valueClass, vid);
				} else {
					value = null;
				}
			}
		}
		try {
			PropertyUtils.setProperty(po, name, value);
		} catch (Exception e) {
			// never
			logger.warn("更新对象时,拷贝属性异常", e);
		}
	}
}
 
Example 8
Project: jadira   File: JpaBaseRepository.java   View Source Code Vote up 5 votes
/**
 * Determines the ID for the entity
 * 
 * @param entity The entity to retrieve the ID for
 * @return The ID
 */
@SuppressWarnings("deprecation") // No good alternative in the Hibernate API yet
protected ID extractId(T entity) {

	final Class<?> entityClass = TypeHelper.getTypeArguments(JpaBaseRepository.class, this.getClass()).get(0);
	final SessionFactory sf = (SessionFactory)(getEntityManager().getEntityManagerFactory());
	final ClassMetadata cmd = sf.getClassMetadata(entityClass);

	final SessionImplementor si = (SessionImplementor)(getEntityManager().getDelegate());

	@SuppressWarnings("unchecked")
	final ID result = (ID) cmd.getIdentifier(entity, si);
	return result;
}
 
Example 9
Project: enterprise-app   File: CustomHbnContainer.java   View Source Code Vote up 4 votes
/**
 * This method gets the value that is stored by the property. The returned object is compatible with the
 * class returned by getType().
 */
@SuppressWarnings("unchecked")
@Override
public Object getValue()
{
	logger.executionTrace();

	final Session session = sessionFactory.getCurrentSession();
	final SessionImplementor sessionImplementor = (SessionImplementor) session;

	if (!sessionFactory.getCurrentSession().contains(pojo))
		pojo = (T) session.get(entityType, (Serializable) getIdForPojo(pojo));

	if (propertyInEmbeddedKey(propertyName))
	{
		final ComponentType identifierType = (ComponentType) classMetadata.getIdentifierType();
		final String[] propertyNames = identifierType.getPropertyNames();

		for (int i = 0; i < propertyNames.length; i++)
		{
			String name = propertyNames[i];

			if (name.equals(propertyName))
			{
				final Object id = classMetadata.getIdentifier(pojo, sessionImplementor);
				return identifierType.getPropertyValue(id, i, EntityMode.POJO);
			}
		}
	}

	final Type propertyType = getPropertyType();
	final Object propertyValue = classMetadata.getPropertyValue(pojo, propertyName);

	if (!propertyType.isAssociationType())
		return propertyValue;

	if (propertyType.isCollectionType())
	{
		if (propertyValue == null)
			return null;

		final HashSet<Serializable> identifiers = new HashSet<Serializable>();
		final Collection<?> pojos = (Collection<?>) propertyValue;

		for (Object object : pojos)
		{
			if (!session.contains(object))
				object = session.merge(object);

			identifiers.add(session.getIdentifier(object));
		}

		return identifiers;
	}

	if (propertyValue == null)
		return null;

	final Class<?> propertyTypeClass = propertyType.getReturnedClass();
	final ClassMetadata metadata = sessionFactory.getClassMetadata(propertyTypeClass);
	final Serializable identifier = metadata.getIdentifier(propertyValue, sessionImplementor);

	return identifier;
}
 
Example 10
Project: caarray   File: UniqueConstraintValidator.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
@SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.ExcessiveMethodLength" })
public boolean isValid(final Object o) {
    UnfilteredCallback unfilteredCallback = new UnfilteredCallback() {
        public Object doUnfiltered(Session s) {
            FlushMode fm = s.getFlushMode();
            try {
                s.setFlushMode(FlushMode.MANUAL);
                Class<?> classWithConstraint
                        = findClassDeclaringConstraint(hibernateHelper.unwrapProxy(o).getClass());
                Criteria crit = s.createCriteria(classWithConstraint);
                ClassMetadata metadata = hibernateHelper.getSessionFactory()
                        .getClassMetadata(classWithConstraint);
                for (UniqueConstraintField field : uniqueConstraint.fields()) {
                    Object fieldVal = metadata.getPropertyValue(o, field.name(), EntityMode.POJO);
                    if (fieldVal == null) {
                        if (field.nullsEqual()) {
                            // nulls are equal, so add it to to criteria
                            crit.add(Restrictions.isNull(field.name()));
                        } else {
                            // nulls are never equal, so uniqueness is automatically satisfied
                            return true;
                        }
                    } else {
                        // special casing for entity-type properties - only include them in the criteria if they are
                        // already
                        // persistent
                        // otherwise, short-circuit the process and return true immediately since if the
                        // entity-type property
                        // is not persistent then it will be a new value and thus different from any currently in 
                        // the db, thus satisfying uniqueness
                        ClassMetadata fieldMetadata = hibernateHelper
                                .getSessionFactory().getClassMetadata(
                                        hibernateHelper.unwrapProxy(fieldVal).getClass());
                        if (fieldMetadata == null
                                || fieldMetadata.getIdentifier(fieldVal, EntityMode.POJO) != null) {
                            crit.add(
                                    Restrictions.eq(field.name(),
                                    ReflectHelper.getGetter(o.getClass(),
                                    field.name())
                                    .get(o)));
                        } else {
                            return true;
                        }
                    }
                }
                // if object is already persistent, then add condition to exclude it matching itself
                Object id = metadata.getIdentifier(o, EntityMode.POJO);
                if (id != null) {
                    crit.add(Restrictions.ne(metadata.getIdentifierPropertyName(), id));
                }

                int numMatches =  crit.list().size();
                return numMatches == 0;
            } finally {
                s.setFlushMode(fm);
            }
        }
    };
    return (Boolean) hibernateHelper.doUnfiltered(unfilteredCallback);

}
 
Example 11
Project: breeze.server.java   File: RelationshipFixer.java   View Source Code Vote up 2 votes
/**
 * Return the property value for the given entity.
 * @param meta
 * @param entity
 * @param propName If null, the identifier property will be returned.
 * @return
 */
private Object getPropertyValue(ClassMetadata meta, Object entity, String propName) {
    if (propName == null || propName == meta.getIdentifierPropertyName()) return meta.getIdentifier(entity, null);
    else return meta.getPropertyValue(entity, propName);
}