Example usage for org.hibernate.metadata ClassMetadata getIdentifier

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

Introduction

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

Prototype

Serializable getIdentifier(Object entity, SharedSessionContractImplementor session);

Source Link

Document

Get the identifier of an instance (throw an exception if no identifier property)

Usage

From source file:ariba.ui.meta.jpa.HibernateContext.java

License:Apache License

public Object getPrimaryKey(Object o) {
    Session session = getSession();//from w ww.j a  va  2 s. c  om
    ClassMetadata classMeta = session.getSessionFactory().getClassMetadata(o.getClass());
    return classMeta.getIdentifier(o, EntityMode.POJO);
}

From source file:at.molindo.esi4j.module.hibernate.HibernateEntityResolver.java

License:Apache License

/**
 * must be called within originating session
 *///from ww  w.  j  ava 2s .c o m
@Override
public ObjectKey toObjectKey(Object entity) {
    SessionFactory factory = getSessionFactory();

    Session session = getCurrentSession(factory);

    String entityName = _entityNames.find(entity.getClass());

    ClassMetadata meta = factory.getClassMetadata(entityName);

    Class<?> type = meta.getMappedClass();

    Serializable id = meta.getIdentifier(entity, (SessionImpl) session);
    Long version = toLongVersion(meta.getVersion(entity));

    return new ObjectKey(type, id, version);
}

From source file:at.molindo.esi4j.module.hibernate.scrolling.DefaultQueryScrollingSession.java

License:Apache License

@Override
public List<?> fetch(Session session, int batchSize) {
    Criteria criteria = session.createCriteria(_type);
    if (_lastId != null) {
        criteria.add(Restrictions.gt("id", _lastId));
    }/* w w  w .  ja  v a 2s  . com*/
    criteria.addOrder(Order.asc("id"));
    criteria.setMaxResults(batchSize);
    criteria.setCacheable(false);

    for (Map.Entry<String, FetchMode> e : _fetchModes.entrySet()) {
        criteria.setFetchMode(e.getKey(), e.getValue());
    }

    List<?> list = criteria.list();

    if (list.size() > 0) {
        ClassMetadata meta = session.getSessionFactory().getClassMetadata(_type);

        Object last = list.get(list.size() - 1);
        _lastId = meta.getIdentifier(last, (SessionImpl) session);
    }

    return list;
}

From source file:br.gov.jfrj.siga.model.Objeto.java

License:Open Source License

public Object _key() {
    Session session = (Session) (em().getDelegate());
    ClassMetadata meta = session.getSessionFactory().getClassMetadata(this.getClass());
    return meta.getIdentifier(this, (SessionImplementor) session);
}

From source file:com.autobizlogic.abl.hibernate.HibernateUtil.java

License:Open Source License

/**
 * Given two persistent beans, which may or may not be proxies, determine whether they refer
 * to the same persistent object. In other words, are they of the same class, and do they
 * have the same primary key?/*from   w  w  w  .  ja v  a 2s .  co  m*/
 * If both beans are null, this will return true.
 */
public static boolean beansHaveSamePK(Object bean1, Object bean2, Session session) {

    if (bean1 == null && bean2 == null)
        return true;

    if (bean1 == null && bean2 != null)
        return false;

    if (bean1 != null && bean2 == null)
        return false;

    if (bean1 == bean2)
        return true;

    String bean1ClassName = getEntityNameForObject(bean1);
    String bean2ClassName = getEntityNameForObject(bean2);
    if (!bean1ClassName.equals(bean2ClassName))
        return false;

    SessionFactory sf = session.getSessionFactory();
    ClassMetadata meta = sf.getClassMetadata(bean1ClassName);
    if (meta == null)
        throw new RuntimeException("Unable to get Hibernate metadata for: " + bean1ClassName);
    Object pk1 = meta.getIdentifier(bean1, (SessionImplementor) session);
    Object pk2 = meta.getIdentifier(bean2, (SessionImplementor) session);
    if (pk1 == null || pk2 == null)
        return false;
    return pk1.equals(pk2);
}

From source file:com.autobizlogic.abl.session.LogicTransactionContext.java

License:Open Source License

/**
 * Given an object, which could be either an entity or a proxy, get its primary key.
 *//*from w  w  w.j a va  2  s .c om*/
public Serializable getPrimaryKeyForObject(Object object) {
    if (object == null)
        return null;

    Serializable fk = null;
    if (object instanceof HibernateProxy) {
        HibernateProxy proxy = (HibernateProxy) object;
        fk = proxy.getHibernateLazyInitializer().getIdentifier();
    } else {
        SessionFactory sessionFactory = session.getSessionFactory();
        ClassMetadata classMeta = sessionFactory.getClassMetadata(object.getClass());
        fk = classMeta.getIdentifier(object, (SessionImplementor) session);
    }
    return fk;
}

From source file:com.javaetmoi.core.persistence.hibernate.LazyLoadingUtil.java

License:Apache License

@SuppressWarnings("unchecked")
private static void deepInflateEntity(final Session currentSession, Object entity, Set<String> recursiveGuard)
        throws HibernateException {
    if (entity == null) {
        return;/*from w  w  w .  j av  a  2  s.  c o m*/
    }

    Class<? extends Object> persistentClass = entity.getClass();
    if (entity instanceof HibernateProxy) {
        persistentClass = ((HibernateProxy) entity).getHibernateLazyInitializer().getPersistentClass();
    }
    ClassMetadata classMetadata = currentSession.getSessionFactory().getClassMetadata(persistentClass);
    if (classMetadata == null) {
        return;
    }
    Serializable identifier = classMetadata.getIdentifier(entity, (AbstractSessionImpl) currentSession);
    String key = persistentClass.getName() + "|" + identifier;

    if (recursiveGuard.contains(key)) {
        return;
    }
    recursiveGuard.add(key);

    if (!Hibernate.isInitialized(entity)) {
        Hibernate.initialize(entity);
    }

    for (int i = 0, n = classMetadata.getPropertyNames().length; i < n; i++) {
        String propertyName = classMetadata.getPropertyNames()[i];
        Type propertyType = classMetadata.getPropertyType(propertyName);
        Object propertyValue = null;
        if (entity instanceof javassist.util.proxy.ProxyObject) {
            // For javassist proxy, the classMetadata.getPropertyValue(..) method return en
            // emppty collection. So we have to call the property's getter in order to call the
            // JavassistLazyInitializer.invoke(..) method that will initialize the collection by
            // loading it from the database.
            propertyValue = callCollectionGetter(entity, propertyName);
        } else {
            propertyValue = classMetadata.getPropertyValue(entity, propertyName, EntityMode.POJO);
        }
        deepInflateProperty(propertyValue, propertyType, currentSession, recursiveGuard);
    }
}

From source file:com.mg.framework.service.DatabaseAuditServiceImpl.java

License:Open Source License

private String entityPropertyToString(Object state, ClassMetadata metadata) {
    if (state != null) {
        Serializable id = metadata.getIdentifier(state, EntityMode.POJO);
        return MessageHelper.infoString(metadata.getEntityName(), id);
    } else/*from   w  w  w. j a va2s .com*/
        return null;
}

From source file:com.mg.framework.service.PersistentObjectHibernate.java

License:Open Source License

public AttributeMap getAllAttributes() {
    org.hibernate.metadata.ClassMetadata meta = getFactory()
            .getClassMetadata(ReflectionUtils.getEntityClass(this));
    String[] props = meta.getPropertyNames();
    Object[] values = meta.getPropertyValues(this, getEntityMode());
    AttributeMap result = new com.mg.framework.support.LocalDataTransferObject();
    for (int i = 0; i < props.length; i++) {
        if (values[i] == LazyPropertyInitializer.UNFETCHED_PROPERTY) {
            //http://issues.m-g.ru/bugzilla/show_bug.cgi?id=4664
            //? ? ?? ? , ?  lazy 
            //??   get  set  ? 
            values[i] = getAttribute(props[i]);
        }//from w  ww  . ja va 2  s. c o m
        result.put(props[i], values[i]);
    }
    //put identifier
    result.put(meta.getIdentifierPropertyName(), meta.getIdentifier(this, getEntityMode()));
    //put custom fields
    if (customFieldsStorage != null)
        result.putAll(customFieldsStorage.getValues());
    return result;
}

From source file:com.oracle.coherence.hibernate.cachestore.HibernateCacheLoader.java

License:CDDL license

/**
 * Load a collection of Hibernate entities given a set of ids (keys)
 *
 * @param keys  the cache keys; specifically, the entity ids
 *
 * @return      the corresponding Hibernate entity instances
 *//*from   w w  w.j  a  v a 2s  .  c  o  m*/
public Map loadAll(Collection keys) {
    ensureInitialized();

    Map results = new HashMap();

    Transaction tx = null;

    Session session = openSession();
    SessionImplementor sessionImplementor = (SessionImplementor) session;

    try {
        tx = session.beginTransaction();

        // Create the query
        String sQuery = getLoadAllQuery();
        Query query = session.createQuery(sQuery);

        // Prevent Hibernate from caching the results
        query.setCacheMode(CacheMode.IGNORE);
        query.setCacheable(false);
        query.setReadOnly(true);

        // Parameterize the query (where :keys = keys)
        query.setParameterList(PARAM_IDS, keys);

        // Need a way to extract the key from an entity that we know
        // nothing about.
        ClassMetadata classMetaData = getEntityClassMetadata();

        // Iterate through the results and place into the return map
        for (Iterator iter = query.list().iterator(); iter.hasNext();) {
            Object entity = iter.next();
            Object id = classMetaData.getIdentifier(entity, sessionImplementor);
            results.put(id, entity);
        }

        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }

        throw ensureRuntimeException(e);
    } finally {
        closeSession(session);
    }

    return results;
}