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

The following are Jave code examples for showing how to use getIdentifierPropertyName() 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: lemon   File: HibernateBasicDao.java   View Source Code Vote up 6 votes
/**
 * 取得对象的主键名,辅助函数.
 * 
 * @param entityClass
 *            实体类型
 * @return 主键名称
 */
public String getIdName(Class entityClass) {
    Assert.notNull(entityClass);
    entityClass = ReflectUtils.getOriginalClass(entityClass);

    ClassMetadata meta = this.getSessionFactory().getClassMetadata(
            entityClass);
    Assert.notNull(meta, "Class " + entityClass
            + " not define in hibernate session factory.");

    String idName = meta.getIdentifierPropertyName();
    Assert.hasText(idName, entityClass.getSimpleName()
            + " has no identifier property define.");

    return idName;
}
 
Example 2
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 3
Project: dachs   File: HibernateLazyIdExtractor.java   View Source Code Vote up 6 votes
@Override
public String[] extractIdPropertyNames(Object entity)
{
    final IdClass idClassAnn = entity.getClass().getAnnotation(IdClass.class);
    if (idClassAnn != null)
    {
        final Class<?> entityClass = idClassAnn.value();
        final List<String> retVal = new ArrayList<>(3);
        ReflectionUtils.doWithFields(entityClass, (f)->
           {
               if (! Modifier.isStatic(f.getModifiers()))
               {
                   retVal.add(f.getName());
               }
           });
        return retVal.toArray(new String[retVal.size()]);
    }
    else
    {
        final ClassMetadata classMetadata = factory.getClassMetadata(entity.getClass());
        final String propertyName = classMetadata.getIdentifierPropertyName();
        return propertyName != null ? new String[]{propertyName} : null;
    }
}
 
Example 4
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 5
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 6
Project: jeecms6   File: HibernateBaseDao.java   View Source Code Vote up 6 votes
/**
 * 将更新对象拷贝至实体对象,并处理many-to-one的更新。
 * 
 * @param updater
 * @param po
 */
private void updaterCopyToPersistentObject(Updater<T> updater, T po,
		ClassMetadata cm) {
	String[] propNames = cm.getPropertyNames();
	String identifierName = cm.getIdentifierPropertyName();
	T bean = updater.getBean();
	Object value;
	for (String propName : propNames) {
		if (propName.equals(identifierName)) {
			continue;
		}
		try {
			value = MyBeanUtils.getSimpleProperty(bean, propName);
			if (!updater.isUpdate(propName, value)) {
				continue;
			}
			cm.setPropertyValue(po, propName, value, POJO);
		} catch (Exception e) {
			throw new RuntimeException(
					"copy property to persistent object failed: '"
							+ propName + "'", e);
		}
	}
}
 
Example 7
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 8
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 9
Project: Lottery   File: HibernateBaseDao.java   View Source Code Vote up 6 votes
/**
 * 将更新对象拷贝至实体对象,并处理many-to-one的更新。
 * 
 * @param updater
 * @param po
 */
private void updaterCopyToPersistentObject(Updater<T> updater, T po,
		ClassMetadata cm) {
	String[] propNames = cm.getPropertyNames();
	String identifierName = cm.getIdentifierPropertyName();
	T bean = updater.getBean();
	Object value;
	for (String propName : propNames) {
		if (propName.equals(identifierName)) {
			continue;
		}
		try {
			value = MyBeanUtils.getSimpleProperty(bean, propName);
			if (!updater.isUpdate(propName, value)) {
				continue;
			}
			cm.setPropertyValue(po, propName, value, POJO);
		} catch (Exception e) {
			throw new RuntimeException(
					"copy property to persistent object failed: '"
							+ propName + "'", e);
		}
	}
}
 
Example 10
Project: ix3   File: MetaDataImplHibernate.java   View Source Code Vote up 5 votes
@Override
public String getPrimaryKeyPropertyName() {
    ClassMetadata classMetadata = getClassMetadata();
    if (classMetadata == null) {
        return null;
    }

    if (classMetadata.hasIdentifierProperty() == true) {
        return classMetadata.getIdentifierPropertyName();
    } else {
        return null;
    }
}
 
Example 11
Project: Ins_fb_pictureSpider_WEB   File: GenericDao.java   View Source Code Vote up 4 votes
/**
 * 取得对象的主键名.
 */
public String getIdName() {
    ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
    return meta.getIdentifierPropertyName();
}
 
Example 12
Project: DWSurvey   File: SimpleHibernateDao.java   View Source Code Vote up 4 votes
@Override
public String getIdName() {
	ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
	return meta.getIdentifierPropertyName();
}
 
Example 13
Project: Shop   File: HibernateRepository.java   View Source Code Vote up 4 votes
/**
 * 取得对象的主键名.
 */
public String getIdName() {
	ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
	return meta.getIdentifierPropertyName();
}
 
Example 14
Project: appBack   File: HibernateDao.java   View Source Code Vote up 4 votes
/**
 * 取得对象的主键名.
 */
public String getIdName() {
    ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
    return meta.getIdentifierPropertyName();
}
 
Example 15
Project: nbone   File: BaseHibernateDao.java   View Source Code Vote up 4 votes
/**
 * 取得对象的主键名.
 */
public String getIdName() {
	ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
	return meta.getIdentifierPropertyName();
}
 
Example 16
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 17
Project: AlgoTrader   File: GrailsHibernateDomainClass.java   View Source Code Vote up 4 votes
/**
 * Contructor to be used by all child classes to create a new instance
 * and get the name right.
 *
 * @param clazz          the Grails class
 * @param sessionFactory The Hibernate SessionFactory instance
 * @param metaData       The ClassMetaData for this class retrieved from the SF
 * @param defaultConstraints The default global constraints definition
 */
public GrailsHibernateDomainClass(Class<?> clazz, SessionFactory sessionFactory, GrailsApplication application, ClassMetadata metaData, Map<String, Object> defaultConstraints) {
	super(clazz, "");
	this.application = application;

	new StandardAnnotationMetadata(clazz);
	String ident = metaData.getIdentifierPropertyName();
	this.defaultConstraints = defaultConstraints;
	if (ident != null) {
		Class<?> identType = getPropertyType(ident);
		this.identifier = new GrailsHibernateDomainClassProperty(this, ident);
		this.identifier.setIdentity(true);
		this.identifier.setType(identType);
		this.propertyMap.put(ident, this.identifier);
	}

	// configure the version property
	final int versionIndex = metaData.getVersionProperty();
	String versionPropertyName = null;
	if (versionIndex > -1) {
		versionPropertyName = metaData.getPropertyNames()[versionIndex];
		this.version = new GrailsHibernateDomainClassProperty(this, versionPropertyName);
		this.version.setType(getPropertyType(versionPropertyName));
	}

	// configure remaining properties
	String[] propertyNames = metaData.getPropertyNames();
	boolean[] propertyNullablility = metaData.getPropertyNullability();
	for (int i = 0; i < propertyNames.length; i++) {
		String propertyName = propertyNames[i];
		if (!propertyName.equals(ident) && !(versionPropertyName != null && propertyName.equals(versionPropertyName))) {
			GrailsHibernateDomainClassProperty prop = new GrailsHibernateDomainClassProperty(this, propertyName);
			prop.setType(getPropertyType(propertyName));
			Type hibernateType = metaData.getPropertyType(propertyName);

			// if its an association type
			if (hibernateType.isAssociationType()) {
				prop.setAssociation(true);
				// get the associated type from the session factory and set it on the property
				AssociationType assType = (AssociationType) hibernateType;
				if (assType instanceof AnyType) {
					continue;
				}
				try {
					String associatedEntity = assType.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
					ClassMetadata associatedMetaData = sessionFactory.getClassMetadata(associatedEntity);
					prop.setRelatedClassType(associatedMetaData.getMappedClass(EntityMode.POJO));
				} catch (MappingException me) {
					// other side must be a value object
					if (hibernateType.isCollectionType()) {
						prop.setRelatedClassType(Collection.class);
					}
				}
				// configure type of relationship
				if (hibernateType.isCollectionType()) {
					prop.setOneToMany(true);
				} else if (hibernateType.isEntityType()) {
					prop.setManyToOne(true);
					// might not really be true, but for our purposes this is ok
					prop.setOneToOne(true);
				}

				prop.setOptional(propertyNullablility[i]);
			}
			this.propertyMap.put(propertyName, prop);
		}
	}

	this.properties = this.propertyMap.values().toArray(new GrailsDomainClassProperty[this.propertyMap.size()]);
	// process the constraints
	evaluateConstraints();
}
 
Example 18
Project: haloDao-Hibernate3   File: HaloDao.java   View Source Code Vote up 4 votes
protected String getIdPropertyName() {
	ClassMetadata meta = getSessionFactory().getClassMetadata(entityType);
	return meta.getIdentifierPropertyName();
}
 
Example 19
Project: snaker-demo   File: SimpleHibernateDao.java   View Source Code Vote up 4 votes
/**
 * 取得对象的主键名.
 */
public String getIdName() {
	ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
	return meta.getIdentifierPropertyName();
}
 
Example 20
Project: yscardII   File: SimpleHibernateDao.java   View Source Code Vote up 4 votes
public String getIdName() {
	ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
	return meta.getIdentifierPropertyName();
}
 
Example 21
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 22
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 23
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;
}
 
Example 24
Project: lakeside-java   File: BaseDao.java   View Source Code Vote up 4 votes
/**
 * 取得对象的主键名.
 */
public String getIdName() {
	ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
	return meta.getIdentifierPropertyName();
}
 
Example 25
Project: jdal   File: HibernateUtils.java   View Source Code Vote up 3 votes
/**
 * Gets the identifier property name of persistent object
 * 
 * @param sessionFactory the hibernate SessionFactory
 * @param obj the persistent object
 * @return the identifier property name
 */
public static String getIdentifierPropertyName(
		SessionFactory sessionFactory, Object obj) {
	
	ClassMetadata cm = getClassMetadata(sessionFactory, obj);

	return cm == null ? null : cm.getIdentifierPropertyName();
	
}
 
Example 26
Project: shj_template   File: BaseDaoImpl.java   View Source Code Vote up 2 votes
/**
 * 获取主键名
 * @author FengJianBo
 * @return
 * 2014年3月21日 下午2:42:49
 */
public String getPkColunmName(){
	ClassMetadata meta = sessionFactory.getCurrentSession().getSessionFactory().getClassMetadata(getEntityClass());
	return meta.getIdentifierPropertyName();
}
 
Example 27
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);
}
 
Example 28
Project: base-framework   File: BasicHibernateDao.java   View Source Code Vote up 2 votes
/**
 * 取得对象的主键名.
 * 
 * @return String
 */
public String getIdName() {
	ClassMetadata meta = sessionFactory.getClassMetadata(entityClass);
	return meta.getIdentifierPropertyName();
}