Example usage for org.hibernate.mapping PersistentClass getProperty

List of usage examples for org.hibernate.mapping PersistentClass getProperty

Introduction

In this page you can find the example usage for org.hibernate.mapping PersistentClass getProperty.

Prototype

public Property getProperty(String propertyName) throws MappingException 

Source Link

Usage

From source file:com.fiveamsolutions.nci.commons.audit.AuditLogInterceptor.java

License:Open Source License

/**
 * Retrieves the column name for the given PersistentClass and fieldName.
 *
 * @param pc/*from w  w w .j  a v  a 2s  . co  m*/
 * @param fieldName
 * @return columnName
 */
private static String getColumnName(PersistentClass pc, String fieldName) {
    if (pc == null) {
        return null;
    }

    String columnName = null;
    Property property = pc.getProperty(fieldName);
    for (Iterator<?> it3 = property.getColumnIterator(); it3.hasNext();) {
        Object o = it3.next();
        if (!(o instanceof Column)) {
            LOG.debug("Skipping non-column (probably a formula");
            continue;
        }
        Column column = (Column) o;
        columnName = column.getName();
        break;
    }
    if (columnName == null) {
        try {
            columnName = getColumnName(pc.getSuperclass(), fieldName);
        } catch (MappingException e) {
            // in this case the annotation / mapping info was at the current class and not the base class
            // but for some reason the column name could not be determined.
            // This will happen when a subclass of an entity uses a joined subclass.
            // in this case just set column Name to null and let the caller default to the property name.
            columnName = null;
        }
    }

    return columnName;
}

From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java

License:Open Source License

private Property getRefProperty(PersistentClass clazzOne, String propertyName) {
    Property refProp;/* w  w  w . ja v a  2  s . co m*/
    //TODO alessio ha senso questo automatismo?
    if (null != clazzOne.getIdentifierProperty()) {
        refProp = clazzOne.getIdentifierProperty();
    } else if (null != clazzOne.getIdentifier()) {
        refProp = ((Component) clazzOne.getIdentifier()).getProperty(propertyName);
    } else {
        refProp = clazzOne.getProperty(propertyName);
    }
    return refProp;
}

From source file:com.netspective.tool.hibernate.document.diagram.HibernateDiagramGenerator.java

License:Open Source License

public HibernateDiagramGenerator(final Configuration configuration,
        final GraphvizDiagramGenerator graphvizDiagramGenerator,
        final HibernateDiagramGeneratorFilter schemaDiagramFilter) throws HibernateDiagramGeneratorException {
    this.configuration = configuration;
    this.graphvizDiagramGenerator = graphvizDiagramGenerator;
    this.diagramFilter = schemaDiagramFilter;

    // the following was copied from org.hibernate.cfg.Configuration.buildMapping() because buildMapping() was private
    this.mapping = new Mapping() {
        /**/*from   w  w  w  .j  a  v a2  s. c om*/
         * Returns the identifier type of a mapped class
         */
        public Type getIdentifierType(String persistentClass) throws MappingException {
            final PersistentClass pc = configuration.getClassMapping(persistentClass);
            if (pc == null)
                throw new MappingException("persistent class not known: " + persistentClass);
            return pc.getIdentifier().getType();
        }

        public String getIdentifierPropertyName(String persistentClass) throws MappingException {
            final PersistentClass pc = configuration.getClassMapping(persistentClass);
            if (pc == null)
                throw new MappingException("persistent class not known: " + persistentClass);
            if (!pc.hasIdentifierProperty())
                return null;
            return pc.getIdentifierProperty().getName();
        }

        public Type getPropertyType(String persistentClass, String propertyName) throws MappingException {
            final PersistentClass pc = configuration.getClassMapping(persistentClass);
            if (pc == null)
                throw new MappingException("persistent class not known: " + persistentClass);
            Property prop = pc.getProperty(propertyName);
            if (prop == null)
                throw new MappingException("property not known: " + persistentClass + '.' + propertyName);
            return prop.getType();
        }
    };

    String dialectName = configuration.getProperty(Environment.DIALECT);
    if (dialectName == null)
        dialectName = org.hibernate.dialect.GenericDialect.class.getName();

    try {
        final Class cls = Class.forName(dialectName);
        this.dialect = (Dialect) cls.newInstance();
    } catch (Exception e) {
        throw new HibernateDiagramGeneratorException(e);
    }

    for (final Iterator classes = configuration.getClassMappings(); classes.hasNext();) {
        final PersistentClass pclass = (PersistentClass) classes.next();
        final Table table = (Table) pclass.getTable();

        tableToClassMap.put(table, pclass);
    }
}

From source file:com.wm.framework.sh.dao.impl.BaseDaoImpl.java

License:Open Source License

protected String getColumnName(Class<?> clazz, String propertyName) {
    PersistentClass persistentClass = getPersistentClass(clazz);
    Property property = persistentClass.getProperty(propertyName);
    Iterator<?> it = property.getColumnIterator();
    if (it.hasNext()) {
        Column column = (Column) it.next();
        return column.getName();
    }/*from w  w w .j  a v  a 2  s  . c  om*/
    return null;
}

From source file:com.xpn.xwiki.store.migration.hibernate.AbstractDropNotNullDataMigration.java

License:Open Source License

@Override
public String getLiquibaseChangeLog() throws DataMigrationException {
    XWikiHibernateBaseStore store = getStore();
    Dialect dialect = store.getDialect();
    Configuration configuration = store.getConfiguration();
    Mapping mapping = configuration.buildMapping();
    PersistentClass pClass = configuration.getClassMapping(this.table.getName());
    Column column = ((Column) pClass.getProperty(this.property).getColumnIterator().next());
    String columnType = column.getSqlType(dialect, mapping);

    StringBuilder builder = new StringBuilder();

    builder.append("<changeSet author=\"xwiki\" id=\"R").append(this.getVersion().getVersion()).append("\">\n");
    builder.append("    <dropNotNullConstraint\n");
    builder.append("            columnDataType=\"").append(columnType).append('"').append('\n');
    builder.append("            columnName=\"").append(column.getName()).append('"').append('\n');
    builder.append("            tableName=\"").append(pClass.getTable().getName()).append("\"/>\n");
    builder.append("</changeSet>");

    return builder.toString();
}

From source file:com.xpn.xwiki.store.migration.hibernate.R40000XWIKI6990DataMigration.java

License:Open Source License

/**
* get column name (first one) of a property of the given pClass.
* @param pClass the persistent class//from www .j  a  v a  2 s .  c  o  m
* @param propertyName the name of the property, or null to return the first column of the key
* @return the column name of the property
*/
private String getColumnName(PersistentClass pClass, String propertyName) {
    if (propertyName != null) {
        return ((Column) pClass.getProperty(propertyName).getColumnIterator().next()).getName();
    }
    return ((Column) pClass.getKey().getColumnIterator().next()).getName();
}

From source file:gov.nih.nci.caarray.validation.UniqueConstraintValidator.java

License:BSD License

/**
 * {@inheritDoc}// w  w  w. j  av  a2  s . c o  m
 */
public void apply(PersistentClass pc) {
    if (this.uniqueConstraint.generateDDLConstraint()) {
        List<Column> columns = new ArrayList<Column>();
        for (UniqueConstraintField field : uniqueConstraint.fields()) {
            Property prop = pc.getProperty(field.name());
            CollectionUtils.addAll(columns, prop.getColumnIterator());
        }
        pc.getTable().createUniqueKey(columns);
    }
}

From source file:it.eng.qbe.datasource.hibernate.HibernatePersistenceManager.java

License:Mozilla Public License

public void updateRecord(JSONObject aRecord, RegistryConfiguration registryConf) {

    SessionFactory sf = dataSource.getHibernateSessionFactory();
    Configuration cfg = dataSource.getHibernateConfiguration();
    Session aSession = null;// w w w  .j a va2 s.  c o  m
    Transaction tx = null;
    try {
        aSession = sf.openSession();
        tx = aSession.beginTransaction();
        String entityName = registryConf.getEntity();
        PersistentClass classMapping = cfg.getClassMapping(entityName);
        ClassMetadata classMetadata = sf.getClassMetadata(entityName);
        String keyName = classMetadata.getIdentifierPropertyName();
        Object key = aRecord.get(keyName);
        Property propertyId = classMapping.getProperty(keyName);

        //casts the id to the appropriate java type
        Object keyConverted = this.convertValue(key, propertyId);

        Object obj = aSession.load(entityName, (Serializable) keyConverted);
        Iterator it = aRecord.keys();
        while (it.hasNext()) {
            String aKey = (String) it.next();
            if (keyName.equals(aKey)) {
                continue;
            }
            Column c = registryConf.getColumnConfiguration(aKey);
            if (c.getSubEntity() != null) {
                // case of foreign key
                Property property = classMapping.getProperty(c.getSubEntity());
                Type propertyType = property.getType();
                if (propertyType instanceof ManyToOneType) {
                    ManyToOneType manyToOnePropertyType = (ManyToOneType) propertyType;
                    String entityType = manyToOnePropertyType.getAssociatedEntityName();
                    Object referenced = getReferencedObject(aSession, entityType, c.getField(),
                            aRecord.get(aKey));
                    Setter setter = property.getSetter(obj.getClass());
                    setter.getMethod().invoke(obj, referenced);
                } else {
                    throw new SpagoBIRuntimeException(
                            "Property " + c.getSubEntity() + " is not a many-to-one relation");
                }
            } else {
                // case of property
                Property property = classMapping.getProperty(aKey);
                Setter setter = property.getSetter(obj.getClass());
                Object valueObj = aRecord.get(aKey);
                if (valueObj != null && !valueObj.equals("")) {
                    Object valueConverted = this.convertValue(valueObj, property);
                    setter.getMethod().invoke(obj, valueConverted);
                }

            }

        }
        aSession.saveOrUpdate(obj);
        tx.commit();

    } catch (Exception e) {

        if (tx != null) {
            tx.rollback();
        }
        throw new RuntimeException(e);
    } finally {
        if (aSession != null) {
            if (aSession.isOpen())
                aSession.close();
        }
    }
}

From source file:it.eng.qbe.model.structure.builder.hibernate.HibernateModelStructureBuilder.java

License:Mozilla Public License

public List addNormalFields(IModelEntity dataMartEntity) {

    ClassMetadata classMetadata;/*from   w  w  w .j a va  2 s .c  om*/
    PersistentClass classMapping;
    String[] propertyNames;
    Property property;
    Type propertyType;

    classMetadata = getDataSource().getHibernateSessionFactory().getClassMetadata(dataMartEntity.getType());
    classMapping = getDataSource().getHibernateConfiguration().getClassMapping(dataMartEntity.getType());
    propertyNames = classMetadata.getPropertyNames();

    List subEntities = new ArrayList();
    String propertyName = null;

    for (int i = 0; i < propertyNames.length; i++) {

        property = classMapping.getProperty(propertyNames[i]);

        // TEST if they are the same: if so use the first invocation
        propertyType = property.getType();

        Iterator columnIterator = property.getColumnIterator();
        Column column;

        if (propertyType instanceof ManyToOneType) { // chiave esterna

            ManyToOneType manyToOnePropertyType = (ManyToOneType) propertyType;
            String entityType = manyToOnePropertyType.getAssociatedEntityName();

            String columnName = null;
            if (columnIterator.hasNext()) {
                column = (Column) columnIterator.next();
                columnName = column.getName(); // ????
            }

            propertyName = propertyNames[i];

            //String entityName = getEntityNameFromEntityType(entityType);
            String entityName = propertyName;
            IModelEntity subentity = new ModelEntity(entityName, null, columnName, entityType,
                    dataMartEntity.getStructure());
            subEntities.add(subentity);

        } else if (propertyType instanceof CollectionType) { // chiave interna

        } else { // normal field
            propertyName = propertyNames[i];

            String type = propertyType.getName();
            int scale = 0;
            int precision = 0;

            if (columnIterator.hasNext()) {
                column = (Column) columnIterator.next();
                scale = column.getScale();
                precision = column.getPrecision();
            }

            IModelField datamartField = dataMartEntity.addNormalField(propertyName);
            datamartField.setType(type);
            datamartField.setPrecision(precision);
            datamartField.setLength(scale);
            propertiesInitializer.addProperties(datamartField);
        }
    }

    return subEntities;
}

From source file:org.babyfish.hibernate.cfg.Configuration.java

License:Open Source License

private void processPersistentClasses() {
    Iterator<PersistentClass> classMappings = this.getClassMappings();
    while (classMappings.hasNext()) { //TODO: please iterate its subclasses.
        PersistentClass persistentClass = classMappings.next();
        Class<?> mappedClass = persistentClass.getMappedClass();
        ObjectModelFactoryProvider provider = Metadatas.getObjectModelFactoryProvider(mappedClass);
        if (provider == null) {
            if (mappedClass.isAnnotationPresent(JPAObjectModelInstrument.class)) {
                throw new IllegalProgramException(LAZY_RESOURCE.get().missInstrument(mappedClass,
                        JPAObjectModelInstrument.class, INSTRUMENT_EXPECTED_POM_SECTION));
            }/*  w w  w  .  j av a  2 s  .  co  m*/
        } else {
            if (!(provider instanceof HibernateObjectModelFactoryProvider)) {
                throw new IllegalProgramException(
                        LAZY_RESOURCE.get().requiredHibernateObjectModelFactoryProvider(mappedClass,
                                HibernateObjectModelFactoryProvider.class));
            }
            HibernateObjectModelMetadata metadata = HibernateMetadatas.of(mappedClass);
            for (org.babyfish.model.metadata.Property property : metadata.getDeclaredProperties().values()) {
                JPAProperty jpaProperty = (JPAProperty) property;
                if (jpaProperty instanceof AssociationProperty) {
                    AssociationProperty associationProperty = (AssociationProperty) jpaProperty;
                    if (associationProperty.getCovarianceProperty() != null) {
                        continue;
                    }
                }
                PropertyInfo ownerProperty = jpaProperty.getOwnerProperty();
                if (ownerProperty == null) {
                    continue;
                }
                Property mappingProperty = persistentClass.getProperty(ownerProperty.getName());
                mappingProperty.setPropertyAccessorName(EntityPropertyAccessor.class.getName());
                Value value = mappingProperty.getValue();
                if (property instanceof AssociationProperty) {
                    JPAAssociationProperty jpaAssociationProperty = (JPAAssociationProperty) property;
                    Class<?> standardReturnType = jpaAssociationProperty.getStandardReturnClass();
                    /*
                     * (1) Don't use jpaAssocationProperty.getHibernateProperty().
                     * This is org.hiberante.mapping.Property, that is org.hibernate.tuple.Property
                     * 
                     * (2) Don't invoke property.getType() or property.getValue().getType()
                     * that will cause the creating of original collection-type before the replacement.
                     */
                    if (jpaAssociationProperty.getCovarianceProperty() == null) {
                        if (standardReturnType == NavigableMap.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Map.class,
                                    MANavigableMapType.class);
                        } else if (standardReturnType == XOrderedMap.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Map.class,
                                    MAOrderedMapType.class);
                        } else if (standardReturnType == Map.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Map.class,
                                    MAOrderedMapType.class);
                        } else if (standardReturnType == NavigableSet.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Set.class,
                                    MANavigableSetType.class);
                        } else if (standardReturnType == XOrderedSet.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Set.class,
                                    MAOrderedSetType.class);
                        } else if (standardReturnType == Set.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Set.class,
                                    MAOrderedSetType.class);
                        } else if (standardReturnType == List.class) {
                            if (org.hibernate.mapping.Bag.class
                                    .isAssignableFrom(mappingProperty.getValue().getClass())) {
                                throw new MappingException(
                                        "In ObjectModel4ORM, Bag proeprty must be declared as java.util.Collection(not java.util.List)");
                            }
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.List.class,
                                    MAListType.class);
                        }
                        if (standardReturnType == Collection.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Bag.class,
                                    MAOrderedSetType.class);
                        }
                        if (value instanceof org.hibernate.mapping.Collection) {
                            org.hibernate.mapping.Collection collection = (org.hibernate.mapping.Collection) value;
                            collection.setTypeParameters(new MACollectionProperties(jpaAssociationProperty,
                                    collection.getTypeParameters()));
                        }

                        if (jpaAssociationProperty.getOwnerIndexProperty() != null) {
                            persistentClass
                                    .getProperty(jpaAssociationProperty.getOwnerIndexProperty().getName())
                                    .setPropertyAccessorName(EntityPropertyAccessor.class.getName());
                        }
                        if (jpaAssociationProperty.getOwnerKeyProperty() != null) {
                            persistentClass.getProperty(jpaAssociationProperty.getOwnerKeyProperty().getName())
                                    .setPropertyAccessorName(EntityPropertyAccessor.class.getName());
                        }
                    }
                }
            }
        }
    }
}