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;
}
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();
}
}
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);
}
}
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));
}
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);
}
Aggregations