Search in sources :

Example 31 with ClassMetadata

use of org.hibernate.metadata.ClassMetadata in project dhis2-core by dhis2.

the class AbstractPropertyIntrospectorService method getPropertiesFromHibernate.

protected Map<String, Property> getPropertiesFromHibernate(Class<?> klass) {
    updateJoinTables();
    ClassMetadata classMetadata = sessionFactory.getClassMetadata(klass);
    // is class persisted with hibernate
    if (classMetadata == null) {
        return new HashMap<>();
    }
    Map<String, Property> properties = new HashMap<>();
    SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory;
    MetadataImplementor metadataImplementor = HibernateMetadata.getMetadataImplementor();
    if (metadataImplementor == null) {
        return new HashMap<>();
    }
    PersistentClass persistentClass = metadataImplementor.getEntityBinding(klass.getName());
    Iterator<?> propertyIterator = persistentClass.getPropertyClosureIterator();
    while (propertyIterator.hasNext()) {
        Property property = new Property(klass);
        property.setRequired(false);
        property.setPersisted(true);
        property.setOwner(true);
        org.hibernate.mapping.Property hibernateProperty = (org.hibernate.mapping.Property) propertyIterator.next();
        Type type = hibernateProperty.getType();
        property.setName(hibernateProperty.getName());
        property.setCascade(hibernateProperty.getCascade());
        property.setCollection(type.isCollectionType());
        property.setSetterMethod(hibernateProperty.getSetter(klass).getMethod());
        property.setGetterMethod(hibernateProperty.getGetter(klass).getMethod());
        if (property.isCollection()) {
            CollectionType collectionType = (CollectionType) type;
            CollectionPersister persister = sessionFactoryImplementor.getCollectionPersister(collectionType.getRole());
            property.setOwner(!persister.isInverse());
            property.setManyToMany(persister.isManyToMany());
            property.setMin(0d);
            property.setMax(Double.MAX_VALUE);
            if (property.isOwner()) {
                property.setOwningRole(collectionType.getRole());
                property.setInverseRole(roleToRole.get(collectionType.getRole()));
            } else {
                property.setOwningRole(roleToRole.get(collectionType.getRole()));
                property.setInverseRole(collectionType.getRole());
            }
        }
        if (SingleColumnType.class.isInstance(type) || CustomType.class.isInstance(type) || ManyToOneType.class.isInstance(type)) {
            Column column = (Column) hibernateProperty.getColumnIterator().next();
            property.setUnique(column.isUnique());
            property.setRequired(!column.isNullable());
            property.setMin(0d);
            property.setMax((double) column.getLength());
            property.setLength(column.getLength());
            if (TextType.class.isInstance(type)) {
                property.setMin(0d);
                property.setMax((double) Integer.MAX_VALUE);
                property.setLength(Integer.MAX_VALUE);
            } else if (IntegerType.class.isInstance(type)) {
                property.setMin(0d);
                property.setMax((double) Integer.MAX_VALUE);
                property.setLength(Integer.MAX_VALUE);
            } else if (LongType.class.isInstance(type)) {
                property.setMin(0d);
                property.setMax((double) Long.MAX_VALUE);
                property.setLength(Integer.MAX_VALUE);
            } else if (DoubleType.class.isInstance(type)) {
                property.setMin(0d);
                property.setMax(Double.MAX_VALUE);
                property.setLength(Integer.MAX_VALUE);
            }
        }
        if (ManyToOneType.class.isInstance(type)) {
            property.setManyToOne(true);
            property.setRequired(property.isRequired() && !property.isCollection());
            if (property.isOwner()) {
                property.setOwningRole(klass.getName() + "." + property.getName());
            } else {
                property.setInverseRole(klass.getName() + "." + property.getName());
            }
        } else if (OneToOneType.class.isInstance(type)) {
            property.setOneToOne(true);
        }
        properties.put(property.getName(), property);
    }
    return properties;
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) HashMap(java.util.HashMap) ManyToOneType(org.hibernate.type.ManyToOneType) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) IntegerType(org.hibernate.type.IntegerType) CustomType(org.hibernate.type.CustomType) CollectionType(org.hibernate.type.CollectionType) ManyToOneType(org.hibernate.type.ManyToOneType) IntegerType(org.hibernate.type.IntegerType) TextType(org.hibernate.type.TextType) LongType(org.hibernate.type.LongType) SingleColumnType(org.hibernate.type.SingleColumnType) OneToOneType(org.hibernate.type.OneToOneType) SetType(org.hibernate.type.SetType) DoubleType(org.hibernate.type.DoubleType) Type(org.hibernate.type.Type) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) Column(org.hibernate.mapping.Column) DoubleType(org.hibernate.type.DoubleType) CollectionType(org.hibernate.type.CollectionType) PersistentClass(org.hibernate.mapping.PersistentClass) OneToOneType(org.hibernate.type.OneToOneType)

Example 32 with ClassMetadata

use of org.hibernate.metadata.ClassMetadata in project opennms by OpenNMS.

the class AbstractDaoHibernate method logExtraSaveOrUpdateExceptionInformation.

/**
 * <p>Parse the {@link DataAccessException} to see if special problems were
 * encountered while performing the query. See issue NMS-5029 for examples of
 * stack traces that can be thrown from these calls.</p>
 * {@see http://issues.opennms.org/browse/NMS-5029}
 */
private void logExtraSaveOrUpdateExceptionInformation(final T entity, final DataAccessException e) {
    Throwable cause = e;
    while (cause.getCause() != null) {
        if (cause.getMessage() != null) {
            if (cause.getMessage().contains("duplicate key value violates unique constraint")) {
                final ClassMetadata meta = getSessionFactory().getClassMetadata(m_entityClass);
                LOG.warn("Duplicate key constraint violation, class: {}, key value: {}", m_entityClass.getName(), meta.getPropertyValue(entity, meta.getIdentifierPropertyName(), EntityMode.POJO));
                break;
            } else if (cause.getMessage().contains("given object has a null identifier")) {
                LOG.warn("Null identifier on object, class: {}: {}", m_entityClass.getName(), entity.toString());
                break;
            }
        }
        cause = cause.getCause();
    }
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata)

Example 33 with ClassMetadata

use of org.hibernate.metadata.ClassMetadata in project openmrs-core by openmrs.

the class HibernateAdministrationDAO method validate.

/**
 * @see org.openmrs.api.db.AdministrationDAO#validate(java.lang.Object, Errors)
 * @should Pass validation if field lengths are correct
 * @should Fail validation if field lengths are not correct
 * @should Fail validation for location class if field lengths are not correct
 * @should Pass validation for location class if field lengths are correct
 */
// @SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
@Override
public void validate(Object object, Errors errors) throws DAOException {
    Class entityClass = object.getClass();
    ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass);
    if (metadata != null) {
        String[] propNames = metadata.getPropertyNames();
        Object identifierType = metadata.getIdentifierType();
        String identifierName = metadata.getIdentifierPropertyName();
        if (identifierType instanceof StringType || identifierType instanceof TextType) {
            int maxLength = getMaximumPropertyLength(entityClass, identifierName);
            String identifierValue = (String) metadata.getIdentifier(object, (SessionImplementor) sessionFactory.getCurrentSession());
            if (identifierValue != null) {
                int identifierLength = identifierValue.length();
                if (identifierLength > maxLength) {
                    errors.rejectValue(identifierName, "error.exceededMaxLengthOfField", new Object[] { maxLength }, null);
                }
            }
        }
        for (String propName : propNames) {
            Type propType = metadata.getPropertyType(propName);
            if (propType instanceof StringType || propType instanceof TextType) {
                String propertyValue = (String) metadata.getPropertyValue(object, propName);
                if (propertyValue != null) {
                    int maxLength = getMaximumPropertyLength(entityClass, propName);
                    int propertyValueLength = propertyValue.length();
                    if (propertyValueLength > maxLength) {
                        errors.rejectValue(propName, "error.exceededMaxLengthOfField", new Object[] { maxLength }, null);
                    }
                }
            }
        }
    }
    FlushMode previousFlushMode = sessionFactory.getCurrentSession().getFlushMode();
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.MANUAL);
    try {
        for (Validator validator : getValidators(object)) {
            validator.validate(object, errors);
        }
    } finally {
        sessionFactory.getCurrentSession().setFlushMode(previousFlushMode);
    }
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) TextType(org.hibernate.type.TextType) StringType(org.hibernate.type.StringType) Type(org.hibernate.type.Type) StringType(org.hibernate.type.StringType) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) PersistentClass(org.hibernate.mapping.PersistentClass) OpenmrsObject(org.openmrs.OpenmrsObject) FlushMode(org.hibernate.FlushMode) Validator(org.springframework.validation.Validator) TextType(org.hibernate.type.TextType)

Example 34 with ClassMetadata

use of org.hibernate.metadata.ClassMetadata in project candlepin by candlepin.

the class AbstractHibernateCurator method lockAndLoad.

/**
 * Refreshes/reloads the given entity and locks it using a pessimistic write lock.
 *
 * @param entity
 *  The entity to lock and load
 *
 * @return
 *  The locked entity
 */
public E lockAndLoad(E entity) {
    if (entity == null) {
        throw new IllegalArgumentException("entity is null");
    }
    // Pull the entity's metadata and identifier, just in case we were passed a detached
    // entity or some such.
    SessionImpl session = (SessionImpl) this.currentSession();
    ClassMetadata metadata = session.getSessionFactory().getClassMetadata(this.entityType);
    if (metadata == null || !metadata.hasIdentifierProperty()) {
        throw new UnsupportedOperationException("lockAndLoad only supports entities with database identifiers");
    }
    return this.lockAndLoadById(this.entityType, metadata.getIdentifier(entity, session));
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) SessionImpl(org.hibernate.internal.SessionImpl)

Example 35 with ClassMetadata

use of org.hibernate.metadata.ClassMetadata in project candlepin by candlepin.

the class AbstractHibernateCurator method lockAndLoad.

/**
 * Locks the given collection of entities, reloading them as necessary.
 *
 * @param entities
 *  A collection of entities to lock
 *
 * @throws RuntimeException
 *  If this method is called for a curator handling an entity type that is not a subclass of
 *  the AbstractHibernateObject class.
 *
 * @return
 *  The collection of locked entities
 */
public Collection<E> lockAndLoad(Iterable<E> entities) {
    if (entities == null) {
        return Collections.<E>emptyList();
    }
    // We redeclare the collection here so we don't require the final modifier in subclass
    // definitions
    final Iterable<E> entityCollection = entities;
    final SessionImpl session = (SessionImpl) this.currentSession();
    final ClassMetadata metadata = session.getSessionFactory().getClassMetadata(this.entityType);
    if (metadata == null || !metadata.hasIdentifierProperty()) {
        throw new UnsupportedOperationException("lockAndLoad only supports entities with database identifiers");
    }
    Iterable<Serializable> iterable = new Iterable<Serializable>() {

        @Override
        public Iterator<Serializable> iterator() {
            return new Iterator<Serializable>() {

                private Iterator<E> entityIterator;

                /* initializer */
                {
                    this.entityIterator = entityCollection.iterator();
                }

                @Override
                public boolean hasNext() {
                    return this.entityIterator.hasNext();
                }

                @Override
                public Serializable next() {
                    E next = this.entityIterator.next();
                    return next != null ? metadata.getIdentifier(next, session) : null;
                }

                @Override
                public void remove() {
                    this.entityIterator.remove();
                }
            };
        }
    };
    return this.lockAndLoadByIds(this.entityType, iterable);
}
Also used : ClassMetadata(org.hibernate.metadata.ClassMetadata) Serializable(java.io.Serializable) Iterator(java.util.Iterator) SessionImpl(org.hibernate.internal.SessionImpl)

Aggregations

ClassMetadata (org.hibernate.metadata.ClassMetadata)58 PersistentClass (org.hibernate.mapping.PersistentClass)23 IClassMetadata (org.jboss.tools.hibernate.runtime.spi.IClassMetadata)21 RootClass (org.hibernate.mapping.RootClass)20 IPOJOClass (org.jboss.tools.hibernate.runtime.spi.IPOJOClass)12 IPersistentClass (org.jboss.tools.hibernate.runtime.spi.IPersistentClass)12 POJOClass (org.hibernate.tool.hbm2x.pojo.POJOClass)11 Test (org.junit.jupiter.api.Test)11 Type (org.hibernate.type.Type)10 Before (org.junit.Before)8 Field (java.lang.reflect.Field)5 AbstractEntityPersister (org.hibernate.persister.entity.AbstractEntityPersister)5 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)4 Session (org.hibernate.Session)4 SessionFactory (org.hibernate.SessionFactory)4 SessionImpl (org.hibernate.internal.SessionImpl)4 ComponentType (org.hibernate.type.ComponentType)4 AbstractClassMetadataFacade (org.jboss.tools.hibernate.runtime.common.AbstractClassMetadataFacade)4 MasterDataEntity (org.mifos.application.master.business.MasterDataEntity)4