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

The following are Jave code examples for showing how to use getIdentifierType() 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: metaworks_framework   File: DynamicDaoHelperImpl.java   View Source Code Vote up 6 votes
@Override
public Map<String, Object> getIdMetadata(Class<?> entityClass, HibernateEntityManager entityManager) {
    Map<String, Object> response = new HashMap<String, Object>();
    SessionFactory sessionFactory = entityManager.getSession().getSessionFactory();
    
    ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass);
    if (metadata == null) {
        return null;
    }
    
    String idProperty = metadata.getIdentifierPropertyName();
    response.put("name", idProperty);
    Type idType = metadata.getIdentifierType();
    response.put("type", idType);

    return response;
}
 
Example 2
Project: SparkCommerce   File: DynamicDaoHelperImpl.java   View Source Code Vote up 6 votes
@Override
public Map<String, Object> getIdMetadata(Class<?> entityClass, HibernateEntityManager entityManager) {
    Map<String, Object> response = new HashMap<String, Object>();
    SessionFactory sessionFactory = entityManager.getSession().getSessionFactory();
    
    ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass);
    if (metadata == null) {
        return null;
    }
    
    String idProperty = metadata.getIdentifierPropertyName();
    response.put("name", idProperty);
    Type idType = metadata.getIdentifierType();
    response.put("type", idType);

    return response;
}
 
Example 3
Project: Lucee4   File: HibernateUtil.java   View Source Code Vote up 6 votes
public static Type getPropertyType(ClassMetadata metaData, String name) throws HibernateException {
	try{
		return  metaData.getPropertyType(name);
	}
	catch(HibernateException he){
		if(name.equalsIgnoreCase(metaData.getIdentifierPropertyName())) 
			return metaData.getIdentifierType();
		
		String[] names = metaData.getPropertyNames();
		for(int i=0;i<names.length;i++){
			if(names[i].equalsIgnoreCase(name))
				return metaData.getPropertyType(names[i]);
		}
		throw he;
	}
}
 
Example 4
Project: Lucee4   File: HibernateUtil.java   View Source Code Vote up 6 votes
public static Type getPropertyType(ClassMetadata metaData, String name, Type defaultValue) {
	try{
		return  metaData.getPropertyType(name);
	}
	catch(HibernateException he){
		if(name.equalsIgnoreCase(metaData.getIdentifierPropertyName())) 
			return metaData.getIdentifierType();
		
		String[] names = metaData.getPropertyNames();
		for(int i=0;i<names.length;i++){
			if(names[i].equalsIgnoreCase(name))
				return metaData.getPropertyType(names[i]);
		}
		return defaultValue;
	}
}
 
Example 5
Project: blcdemo   File: DynamicDaoHelperImpl.java   View Source Code Vote up 6 votes
@Override
public Map<String, Object> getIdMetadata(Class<?> entityClass, HibernateEntityManager entityManager) {
    entityClass = getNonProxyImplementationClassIfNecessary(entityClass);
    Map<String, Object> response = new HashMap<String, Object>();
    SessionFactory sessionFactory = entityManager.getSession().getSessionFactory();
    
    ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass);
    if (metadata == null) {
        return null;
    }
    
    String idProperty = metadata.getIdentifierPropertyName();
    response.put("name", idProperty);
    Type idType = metadata.getIdentifierType();
    response.put("type", idType);

    return response;
}
 
Example 6
Project: hql-builder   File: HqlServiceImpl.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public <T extends Serializable, I extends Serializable> T get(Class<T> type, I id) {
    Object idv = id;
    String name = type.getName();
    ClassMetadata classMetadata = (ClassMetadata) new MetadataResolver().getAllClassMetadata(sessionFactory).get(name);
    String oid = classMetadata.getIdentifierPropertyName();
    if (id instanceof String) {
        IdentifierType<?> identifierType = (IdentifierType<?>) classMetadata.getIdentifierType();
        if (!(identifierType instanceof StringType)) {
            try {
                idv = identifierType.stringToObject((String) id);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    QueryParameters hql = new QueryParameters("from " + name + " where " + oid + "=:" + oid,
            new QueryParameter().setName(oid).setValueTypeText(idv));
    logger.debug("hql={}", hql);
    List<Serializable> value = execute(hql).getResults().getValue();
    return (T) (value.isEmpty() ? null : value.get(0));
}
 
Example 7
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 8
Project: breeze.server.java   File: RelationshipFixer.java   View Source Code Vote up 5 votes
/**
 * Connect the related entities based on the foreign key values.
 * Note that this may cause related entities to be loaded from the DB if they are not already in the session.
 * @param entityInfo Entity that will be saved
 * @param meta Metadata about the entity type
 */
private void processRelationships(EntityInfo entityInfo, ClassMetadata meta) {
    addToGraph(entityInfo, null); // make sure every entity is in the graph
    String[] propNames = meta.getPropertyNames();
    Type[] propTypes = meta.getPropertyTypes();

    Type propType = meta.getIdentifierType();
    if (propType != null) {
        processRelationship(meta.getIdentifierPropertyName(), propType, entityInfo, meta);
    }

    for (int i = 0; i < propNames.length; i++) {
        processRelationship(propNames[i], propTypes[i], entityInfo, meta);
    }
}
 
Example 9
Project: Lucee4   File: HibernateORMSession.java   View Source Code Vote up 4 votes
private Object loadByExample(PageContext pc, Object obj,  boolean unique) throws PageException {
	Component cfc=HibernateCaster.toComponent(obj);
	Key dsn = KeyImpl.init(ORMUtil.getDataSourceName(pc, cfc));
	ComponentScope scope = cfc.getComponentScope();
	String name=HibernateCaster.getEntityName(cfc);
	Session sess = getSession(dsn);
	Object rtn=null;

	try{
		//trans.begin();
		
		ClassMetadata metaData = sess.getSessionFactory().getClassMetadata(name);
		String idName = metaData.getIdentifierPropertyName();
		Type idType = metaData.getIdentifierType();
	 
		Criteria criteria=sess.createCriteria(name);
		if(!Util.isEmpty(idName)){
			Object idValue = scope.get(CommonUtil.createKey(idName),null);
			if(idValue!=null){
				criteria.add(Restrictions.eq(idName, HibernateCaster.toSQL(idType, idValue,null)));
			}
		}
		criteria.add(Example.create(cfc));
     
     	// execute
		
		if(!unique){
			rtn = criteria.list();
		}
		else {
			//Map map=(Map) criteria.uniqueResult();
			rtn= criteria.uniqueResult();
		}
	 }
	 catch(Throwable t){
		lucee.commons.lang.ExceptionUtil.rethrowIfNecessary(t);
		// trans.rollback();
		throw CommonUtil.toPageException(t);
	 }
	 //trans.commit();

	 return rtn;
}
 
Example 10
Project: further-open-core   File: HibernateDistinctIdExecutor.java   View Source Code Vote up 4 votes
/**
 * @param request
 * @return
 * @see edu.utah.further.core.chain.AbstractRequestHandler#process(edu.utah.further.core.api.chain.ChainRequest)
 * @see http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
 */
@Override
public boolean process(final ChainRequest request)
{
	final HibernateExecReq executionReq = new HibernateExecReq(request);

	// Validate required input
	final GenericCriteria hibernateCriteria = executionReq.getResult();
	notNull(hibernateCriteria, "Expected Hibernate criteria");

	final Class<? extends PersistentEntity<?>> domainClass = executionReq
			.getRootEntity();
	final Class<? extends PersistentEntity<?>> entityClass = dao
			.getEntityClass(domainClass);

	notNull(entityClass, "Expected root entity class");

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

	final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
	final String identifierName = classMetadata.getIdentifierPropertyName();
	final Type identifierType = classMetadata.getIdentifierType();

	// A hack to obtain projections out of the critieria by casting to the Hibernate
	// implementation. TODO: improve adapter to do that via interface access
	final ProjectionList projectionList = Projections.projectionList();
	final Projection existingProjection = ((CriteriaImpl) hibernateCriteria
			.getHibernateCriteria()).getProjection();

	if (existingProjection != null && !overrideExistingProjection)
	{
		return false;
	}

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

		// Add distinct to the first property
		projectionList.add(
				Projections.distinct(Property.forName(identifierName
						+ PROPERTY_SCOPE_CHAR + idPropertyNames[0])),
				idPropertyNames[0]);

		// Add the remaining properties to the projection list
		for (int i = 1; i < idPropertyNames.length; i++)
		{
			projectionList.add(
					Property.forName(identifierName + PROPERTY_SCOPE_CHAR
							+ idPropertyNames[i]), idPropertyNames[i]);
		}

		hibernateCriteria.setProjection(projectionList);
		hibernateCriteria.setResultTransformer(new AliasToBeanResultTransformer(
				ReflectionUtils.findField(entityClass, identifierName).getType()));
	}
	else
	{
		// 'this' required to avoid HHH-817
		projectionList.add(Projections.distinct(Property.forName(THIS_CONTEXT
				+ identifierName)));
		hibernateCriteria.setProjection(projectionList);
	}

	executionReq.setResult(hibernateCriteria);

	return false;
}
 
Example 11
Project: further-open-core   File: HibernateCountSearchQueryExecutor.java   View Source Code Vote up 4 votes
@SuppressWarnings("boxing")
@Override
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;
}
 
Example 12
Project: further-open-core   File: HibernateLoadByIdExecutor.java   View Source Code Vote up 4 votes
/**
 * @param request
 * @return
 * @see edu.utah.further.core.chain.AbstractRequestHandler#process(edu.utah.further.core.api.chain.ChainRequest)
 */
@Override
public boolean process(final ChainRequest request)
{
	// Read input arguments
	final HibernateExecReq executionReq = new HibernateExecReq(request);
	final SessionFactory sessionFactory = executionReq.getSessionFactory();
	notNull(sessionFactory, "Expected SessionFactory");

	final Class<? extends PersistentEntity<?>> rootEntity = executionReq
			.getRootEntity();
	notNull(rootEntity, "Expected root entity class");

	// Read the search criteria's root entity meta data
	final List<Object> list = executionReq.getResult();
	final Object[] listArray = CollectionUtil.toArrayNullSafe(list);
	final ClassMetadata classMetadata = sessionFactory.getClassMetadata(rootEntity);
	final String identifierName = classMetadata.getIdentifierPropertyName();
	final Type identifierType = classMetadata.getIdentifierType();
	final int numTypes = listArray.length;
	final Type[] types = new Type[numTypes];
	for (int i = 0; i < numTypes; i++)
	{
		types[i] = identifierType;
	}

	// Build Hibernate criteria
	final GenericCriteria criteria = GenericCriteriaFactory.criteria(
			CriteriaType.CRITERIA, rootEntity, sessionFactory.getCurrentSession());
	if (identifierType.isComponentType())
	{
		final String sqlInClause = HibernateUtil.sqlRestrictionCompositeIn(
				rootEntity, sessionFactory, numTypes);
		criteria.add(Restrictions.sqlRestriction(sqlInClause, listArray, types));
	}
	else
	{
		final int size = list.size();
		if (size > MAX_IN)
		{
			// Create a disjunction of IN clauses. Add MAX_IN elements at a time to
			// each IN clause (except the last IN, whose size is size % MAX_IN).
			final Junction junction = Restrictions.disjunction();
			for (int i = 0; i < size; i += MAX_IN)
			{
				junction.add(Restrictions.in(THIS + identifierName,
						list.subList(i, Math.max(size, MAX_IN + i))));
			}
			criteria.add(junction);
		}
		else
		{
			// Single chunk, add directly as a criterion without the junction trick
			criteria.add(Restrictions.in(THIS + identifierName, list));
		}

	}

	executionReq.setResult(criteria);
	return false;
}