Example usage for org.hibernate.persister.entity EntityPersister getEntityMetamodel

List of usage examples for org.hibernate.persister.entity EntityPersister getEntityMetamodel

Introduction

In this page you can find the example usage for org.hibernate.persister.entity EntityPersister getEntityMetamodel.

Prototype

EntityMetamodel getEntityMetamodel();

Source Link

Document

Retrieve the underlying entity metamodel instance...

Usage

From source file:cc.alcina.framework.entity.impl.jboss.JPAHibernateImpl.java

License:Apache License

@Override
public Object beforeSpecificSetId(EntityManager entityManager, Object toPersist) throws Exception {
    SessionImplementor session = (SessionImplementor) entityManager.getDelegate();
    EntityPersister persister = session.getEntityPersister(toPersist.getClass().getName(), toPersist);
    IdentifierGenerator identifierGenerator = persister.getIdentifierGenerator();
    IdentifierProperty ip = persister.getEntityMetamodel().getIdentifierProperty();
    IdentifierValue backupUnsavedValue = setUnsavedValue(ip, IdentifierValue.ANY, new UseEntityIdGenerator());
    return new SavedId(ip, backupUnsavedValue, identifierGenerator);
}

From source file:com.corundumstudio.hibernate.dsc.QueryCacheEntityListener.java

License:Apache License

private Set<Entry<String, QueryListenerEntry>> getValue(EntityPersister persister) {
    EntityMetamodel entityMetamodel = persister.getEntityMetamodel();
    Class<?> clazz = entityMetamodel.getEntityType().getReturnedClass();
    Map<String, QueryListenerEntry> values = map.get(clazz);
    if (values == null) {
        return Collections.emptySet();
    }/*from  www .j  a  va2  s  . co m*/
    return values.entrySet();
}

From source file:org.babyfish.hibernate.collection.spi.persistence.SetBasePersistence.java

License:Open Source License

/**
 * This method is used to replace /* w  ww . j a va 2 s  . com*/
 * "org.hibernate.collection.AbstractPersistentCollection#readElementExistence(Object element)"
 * @param element The example element to be read
 * @return The ref or readed element
 * <ul>
 *  <li>NonNull: Read successfully, check the value of ref to check the read value is null or not</li>
 *  <li>Null: Read failed</li>
 * </ul>
 */
@SuppressWarnings("unchecked")
public Ref<E> visionallyRead(E element) {

    Arguments.mustNotBeNull("element", element);
    String role = this.getNonNullRole();

    SessionImplementor session = this.getSession();
    if (session == null || !session.isOpen() || !session.isConnected()) {
        return null;
    }

    SessionFactoryImplementor sessionFactory = session.getFactory();
    QueryableCollection collection = (QueryableCollection) sessionFactory.getCollectionPersister(role);
    EntityPersister elementPersister = collection.getElementPersister();
    Object elementId = elementPersister.getIdentifier(element, this.getSession());
    if (elementId == null) {
        return new Ref<>();
    }
    if (elementPersister.getEntityMetamodel().getIdentifierProperty().getUnsavedValue()
            .isUnsaved((Serializable) elementId)) {
        return new Ref<>();
    }

    CriteriaImpl criteria = new CriteriaImpl(elementPersister.getEntityName(), session);

    /*
     * Add the condition of element.
     */
    criteria.add(Restrictions.idEq(elementId));

    //ownerKey, not ownerId
    Object ownerKey = collection.getCollectionType().getKeyOfOwner(this.getOwner(), session);
    //In Hibernate, isOneToMany means that there is no middle table
    //The @OneToMany of JPA with middle table is consider as many-to-many in Hibernate
    if (sessionFactory.getCollectionPersister(role).isOneToMany()) {
        String[] joinOwnerColumns = collection.getKeyColumnNames();
        StringBuilder sqlBuilder = new StringBuilder();
        for (int i = 0; i < joinOwnerColumns.length; i++) {
            if (i != 0) {
                sqlBuilder.append(" and ");
            }
            sqlBuilder.append("{alias}.").append(joinOwnerColumns[i]).append(" = ?");
        }
        criteria.add(Restrictions.sqlRestriction(sqlBuilder.toString(), ownerKey, collection.getKeyType()));
    } else {
        String lhsPropertyName = collection.getCollectionType().getLHSPropertyName();
        int lhsPropertyIndex = -1;
        if (lhsPropertyName != null) {
            String[] propertyNames = collection.getOwnerEntityPersister().getPropertyNames();
            for (int i = propertyNames.length - 1; i >= 0; i--) {
                if (propertyNames[i].equals(lhsPropertyName)) {
                    lhsPropertyIndex = i;
                    break;
                }
            }
        }
        String[] lhsColumnNames = JoinHelper.getLHSColumnNames(collection.getCollectionType(), lhsPropertyIndex,
                (OuterJoinLoadable) elementPersister, sessionFactory);
        String[] joinElementColumnNames = collection.getElementColumnNames();
        String[] joinOwnerColumnNames = collection.getKeyColumnNames();
        StringBuilder subQueryBuilder = new StringBuilder();
        subQueryBuilder.append("exists(select * from ").append(collection.getTableName()).append(" as ")
                .append(MIDDLE_TABLE_ALIAS).append(" where ");
        for (int i = 0; i < joinElementColumnNames.length; i++) {
            if (i != 0) {
                subQueryBuilder.append(" and ");
            }
            subQueryBuilder.append("{alias}.").append(lhsColumnNames[i]).append(" = ")
                    .append(MIDDLE_TABLE_ALIAS).append('.').append(joinElementColumnNames[i]);
        }
        for (int i = 0; i < joinOwnerColumnNames.length; i++) {
            subQueryBuilder.append(" and ").append(MIDDLE_TABLE_ALIAS).append(".")
                    .append(joinOwnerColumnNames[i]).append(" = ?");
        }
        subQueryBuilder.append(')');
        criteria.add(
                Restrictions.sqlRestriction(subQueryBuilder.toString(), ownerKey, collection.getKeyType()));
    }
    FlushMode oldFlushMode = session.getFlushMode();
    session.setFlushMode(FlushMode.MANUAL);
    try {
        return new Ref<>((E) criteria.uniqueResult());
    } finally {
        session.setFlushMode(oldFlushMode);
    }
}

From source file:org.babyfish.hibernate.internal.ImplicitCollectionJoins.java

License:Open Source License

private boolean hasImplicitCollectionJoins1(String entityName, Map<String, Boolean> contextMap) {
    EntityPersister persister = this.factory.getEntityPersister(entityName);
    for (NonIdentifierAttribute nonIdAttribute : persister.getEntityMetamodel().getProperties()) {
        Type propertyType = nonIdAttribute.getType();
        if (nonIdAttribute.getFetchMode() == FetchMode.JOIN) {
            if (propertyType.isCollectionType()) { //find collection with {fetch = "join"}
                return true;
            }/* w w w  . j  a  v a  2s . c o m*/
            if (propertyType instanceof AssociationType) {
                String childEntityName = ((AssociationType) propertyType).getAssociatedEntityName(this.factory);
                if (this.hasImplicitCollectionJoins0(childEntityName, contextMap)) {
                    return true;
                }
            }
        } else if (propertyType instanceof CompositeType) {
            if (this.hasImplicitCollectionJoins0((CompositeType) propertyType, contextMap)) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.entitymanager.HibernateCleaner.java

License:Apache License

protected void performConvert(Object originalBean, Object targetBean, Field[] fields, Method method,
        HibernateEntityManager em, PlatformTransactionManager txManager) throws Throwable {
    SessionFactory sessionFactory = em.getSession().getSessionFactory();
    ClassMetadata metadata = sessionFactory.getClassMetadata(originalBean.getClass());
    String idProperty = metadata.getIdentifierPropertyName();
    if (!typePool.containsKey(originalBean.getClass().getName())) {
        List<String> propertyNames = new ArrayList<String>();
        for (String propertyName : metadata.getPropertyNames()) {
            propertyNames.add(propertyName);
        }/*from   w w w.  jav a2 s . com*/
        propertyNames.add(idProperty);
        List<Type> propertyTypes = new ArrayList<Type>();
        Type idType = metadata.getIdentifierType();
        for (Type propertyType : metadata.getPropertyTypes()) {
            propertyTypes.add(propertyType);
        }
        propertyTypes.add(idType);
        Map<String, Type> types = new HashMap<String, Type>();
        int j = 0;
        for (String propertyName : propertyNames) {
            types.put(propertyName, propertyTypes.get(j));
            j++;
        }
        typePool.put(originalBean.getClass().getName(), types);
    }
    Map<String, Type> types = (Map<String, Type>) typePool.get(originalBean.getClass().getName());
    Field idField = null;
    for (Field field : fields) {
        if (types.containsKey(field.getName())) {
            field.setAccessible(true);
            Type fieldType = types.get(field.getName());
            if (fieldType.isCollectionType() || fieldType.isAnyType()) {
                //field.set(targetBean, null);
                //do nothing
            } else if (fieldType.isEntityType()) {
                Object newOriginalBean = field.get(originalBean);
                if (newOriginalBean == null) {
                    field.set(targetBean, null);
                } else {
                    Object newTargetBean = newOriginalBean.getClass().newInstance();
                    field.set(targetBean, newTargetBean);
                    Field[] newFields = getFields(newOriginalBean.getClass());
                    performConvert(newOriginalBean, newTargetBean, newFields, method, em, txManager);
                }
            } else {
                field.set(targetBean, field.get(originalBean));
            }
            if (field.getName().equals(idProperty)) {
                idField = field;
            }
        }
    }
    if (txManager != null) {
        Object temp = null;
        if (idField == null) {
            throw new Exception(
                    "Unable to find an identity field for the entity: " + originalBean.getClass().getName());
        }
        final Serializable primaryKey = (Serializable) idField.get(originalBean);
        if (primaryKey != null) {
            temp = em.find(originalBean.getClass(), primaryKey);
        }

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

        TransactionStatus status = txManager.getTransaction(def);
        try {
            if (primaryKey != null) {
                if (temp != null && method.getName().equals("merge")) {
                    targetBean = em.merge(targetBean);
                } else {
                    SessionImplementor session = (SessionImplementor) em.getDelegate();
                    EntityPersister persister = session.getEntityPersister(targetBean.getClass().getName(),
                            targetBean);
                    IdentifierProperty ip = persister.getEntityMetamodel().getIdentifierProperty();
                    synchronized (ip) {
                        IdentifierValue backupUnsavedValue = setUnsavedValue(ip, IdentifierValue.ANY);
                        em.persist(targetBean);
                        setUnsavedValue(ip, backupUnsavedValue);
                    }
                }
            } else {
                targetBean = method.invoke(em, targetBean);
            }
        } catch (Throwable ex) {
            txManager.rollback(status);
            throw ex;
        }
        txManager.commit(status);
    }
}