Java Code Examples for org.hibernate.metadata.ClassMetadata.getPropertyNames()
The following are Jave code examples for showing how to use
getPropertyNames() of the
org.hibernate.metadata.ClassMetadata
class.
You can vote up the examples you like. Your votes will be used in our system to get
more good examples.
+ Save this method
Example 1
Project: dorset-framework File: HibernateServiceTest.java View Source Code | 6 votes |
@Test public void testCreationOfSessionFactory() { Properties props = getProperties(); Config conf = ConfigFactory.parseProperties(props); hs = new HibernateService(conf); SessionFactory sf = hs.getSessionFactory(); assertNotNull(sf); assertFalse(sf.isClosed()); // traverse through the session factory to get at configuration values SessionFactoryOptions sfo = sf.getSessionFactoryOptions(); StandardServiceRegistry ssr = sfo.getServiceRegistry(); ConfigurationService cs = ssr.getService(ConfigurationService.class); assertEquals(props.getProperty("hibernate.connection.driver_class"), cs.getSetting("hibernate.connection.driver_class", StandardConverters.STRING)); assertEquals(props.getProperty("hibernate.connection.url"), cs.getSetting("hibernate.connection.url", StandardConverters.STRING)); assertEquals(props.getProperty("hibernate.dialect"), cs.getSetting("hibernate.dialect", StandardConverters.STRING)); assertEquals(props.getProperty("hibernate.hbm2ddl.auto"), cs.getSetting("hibernate.hbm2ddl.auto", StandardConverters.STRING)); // check mapping ClassMetadata cm = sf.getClassMetadata(TestObject.class); String[] names = cm.getPropertyNames(); assertEquals(1, names.length); assertEquals("name", names[0]); assertEquals("string", cm.getPropertyType("name").getName()); }
Example 2
Project: jeecms6 File: HibernateBaseDao.java View Source Code | 6 votes |
/** * 将更新对象拷贝至实体对象,并处理many-to-one的更新。 * * @param updater * @param po */ private void updaterCopyToPersistentObject(Updater<T> updater, T po, ClassMetadata cm) { String[] propNames = cm.getPropertyNames(); String identifierName = cm.getIdentifierPropertyName(); T bean = updater.getBean(); Object value; for (String propName : propNames) { if (propName.equals(identifierName)) { continue; } try { value = MyBeanUtils.getSimpleProperty(bean, propName); if (!updater.isUpdate(propName, value)) { continue; } cm.setPropertyValue(po, propName, value, POJO); } catch (Exception e) { throw new RuntimeException( "copy property to persistent object failed: '" + propName + "'", e); } } }
Example 3
Project: Lucee4 File: HibernateUtil.java View Source Code | 6 votes |
public static Type getPropertyType(ClassMetadata metaData, String name) throws HibernateException { try{ return metaData.getPropertyType(name); } catch(HibernateException he){ if(name.equalsIgnoreCase(metaData.getIdentifierPropertyName())) return metaData.getIdentifierType(); String[] names = metaData.getPropertyNames(); for(int i=0;i<names.length;i++){ if(names[i].equalsIgnoreCase(name)) return metaData.getPropertyType(names[i]); } throw he; } }
Example 4
Project: Lucee4 File: HibernateUtil.java View Source Code | 6 votes |
public static Type getPropertyType(ClassMetadata metaData, String name, Type defaultValue) { try{ return metaData.getPropertyType(name); } catch(HibernateException he){ if(name.equalsIgnoreCase(metaData.getIdentifierPropertyName())) return metaData.getIdentifierType(); String[] names = metaData.getPropertyNames(); for(int i=0;i<names.length;i++){ if(names[i].equalsIgnoreCase(name)) return metaData.getPropertyType(names[i]); } return defaultValue; } }
Example 5
Project: dorset-framework File: HibernateServiceTest.java View Source Code | 6 votes |
@Test public void testCreationOfSessionFactory() { Properties props = getProperties(); Config conf = ConfigFactory.parseProperties(props); hs = new HibernateService(conf); SessionFactory sf = hs.getSessionFactory(); assertNotNull(sf); assertFalse(sf.isClosed()); // traverse through the session factory to get at configuration values SessionFactoryOptions sfo = sf.getSessionFactoryOptions(); StandardServiceRegistry ssr = sfo.getServiceRegistry(); ConfigurationService cs = ssr.getService(ConfigurationService.class); assertEquals(props.getProperty("hibernate.connection.driver_class"), cs.getSetting("hibernate.connection.driver_class", StandardConverters.STRING)); assertEquals(props.getProperty("hibernate.connection.url"), cs.getSetting("hibernate.connection.url", StandardConverters.STRING)); assertEquals(props.getProperty("hibernate.dialect"), cs.getSetting("hibernate.dialect", StandardConverters.STRING)); assertEquals(props.getProperty("hibernate.hbm2ddl.auto"), cs.getSetting("hibernate.hbm2ddl.auto", StandardConverters.STRING)); // check mapping ClassMetadata cm = sf.getClassMetadata(TestObject.class); String[] names = cm.getPropertyNames(); assertEquals(1, names.length); assertEquals("name", names[0]); assertEquals("string", cm.getPropertyType("name").getName()); }
Example 6
Project: openeos File: HibernateAnnotationsMixedDictionaryService.java View Source Code | 6 votes |
private void loadClassDefinition(String className) { if (classDefinitions.containsKey(className)) return; //For the flys // PersistentClass persistent = configuration.getClassMapping(className); ClassMetadata metadata = sessionFactory.getClassMetadata(className); if (metadata == null) { return; } HibernateAnnotationsMixedClassDefinitionImpl classDefImpl = new HibernateAnnotationsMixedClassDefinitionImpl( entityToStringService, sessionFactory, metadata.getMappedClass()); String[] propertyNames = metadata.getPropertyNames(); classDefImpl.setIdPropertyDefinition(createPropertyDefinition(metadata.getIdentifierPropertyName(), metadata.getIdentifierType(), metadata)); for (String propertyName : propertyNames) { IPropertyDefinition propertyDef = createPropertyDefinition(propertyName, metadata.getPropertyType(propertyName), metadata); classDefImpl.addPropertyDefinition(propertyDef); } classDefinitions.put(className, classDefImpl); }
Example 7
Project: breeze.server.java File: HibernateSaveProcessor.java View Source Code | 6 votes |
/** * Restore the old value of the concurrency column so Hibernate will save the entity. * Otherwise it will complain because Breeze has already changed the value. * @param entityInfo * @param classMeta */ protected void restoreOldVersionValue(EntityInfo entityInfo, ClassMetadata classMeta) { if (entityInfo.originalValuesMap == null || entityInfo.originalValuesMap.size() == 0) return; int vcol = classMeta.getVersionProperty(); String vname = classMeta.getPropertyNames()[vcol]; if (entityInfo.originalValuesMap.containsKey(vname)) { Object oldVersion = entityInfo.originalValuesMap.get(vname); Object entity = entityInfo.entity; if (oldVersion == null) { _possibleErrors.add("Hibernate does not support 'null' version properties. " + "Entity: " + entity + ", Property: " + vname); } Class versionClazz = classMeta.getPropertyTypes()[vcol].getReturnedClass(); DataType dataType = DataType.fromClass(versionClazz); Object oldValue = DataType.coerceData(oldVersion, dataType); classMeta.setPropertyValue(entity, vname, oldValue); } }
Example 8
Project: Lottery File: HibernateBaseDao.java View Source Code | 6 votes |
/** * 将更新对象拷贝至实体对象,并处理many-to-one的更新。 * * @param updater * @param po */ private void updaterCopyToPersistentObject(Updater<T> updater, T po, ClassMetadata cm) { String[] propNames = cm.getPropertyNames(); String identifierName = cm.getIdentifierPropertyName(); T bean = updater.getBean(); Object value; for (String propName : propNames) { if (propName.equals(identifierName)) { continue; } try { value = MyBeanUtils.getSimpleProperty(bean, propName); if (!updater.isUpdate(propName, value)) { continue; } cm.setPropertyValue(po, propName, value, POJO); } catch (Exception e) { throw new RuntimeException( "copy property to persistent object failed: '" + propName + "'", e); } } }
Example 9
Project: geomajas-project-server File: HibernateEntityMapper.java View Source Code | 6 votes |
/** * Construct a entity collection. * * @param parentMetadata parent meta data * @param childMetadata child meta data * @param parent parent object * @param objects child objects */ public HibernateEntityCollection(ClassMetadata parentMetadata, ClassMetadata childMetadata, Object parent, Collection<?> objects) { this.objects = objects; int i = 0; for (Type type : childMetadata.getPropertyTypes()) { if (type instanceof ManyToOneType) { ManyToOneType mto = (ManyToOneType) type; if (mto.getAssociatedEntityName().equals(parentMetadata.getEntityName())) { parentName = childMetadata.getPropertyNames()[i]; } } i++; } this.metadata = childMetadata; this.parent = parent; }
Example 10
Project: xap-openspaces File: AbstractHibernateSpaceSynchronizationEndpoint.java View Source Code | 5 votes |
/** * Filter from the input map the unmapped field of this entity * * @param entityName * @param itemValues map of properties to filter * */ protected Map<String, Object> filterItemValue(String entityName, Map<String, Object> itemValues) { ClassMetadata classMetadata = getSessionFactory().getClassMetadata(entityName); String[] propertyNames = classMetadata.getPropertyNames(); List<String> names = Arrays.asList(propertyNames); HashMap<String, Object> filteredItems = new HashMap<String, Object>(); Iterator<Entry<String, Object>> iterator = itemValues.entrySet().iterator(); while(iterator.hasNext()){ Entry<String, Object> next = iterator.next(); if (names.contains(next.getKey())){ filteredItems.put(next.getKey(), next.getValue()); } } return filteredItems; }
Example 11
Project: xap-openspaces File: AbstractHibernateExternalDataSource.java View Source Code | 5 votes |
/** * Filter from the input map the unmapped field of this entity * * @param entityName * @param itemValues map of properties to filter * */ protected Map<String, Object> filterItemValue( String entityName, Map<String, Object> itemValues){ ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityName); String[] propertyNames = classMetadata.getPropertyNames(); List<String> names = Arrays.asList(propertyNames); Iterator<String> iterator = itemValues.keySet().iterator(); while(iterator.hasNext()){ if(!names.contains(iterator.next())) iterator.remove(); } return itemValues; }
Example 12
Project: cacheonix-core File: Printer.java View Source Code | 5 votes |
/** * @param entity an actual entity object, not a proxy! */ public String toString(Object entity, EntityMode entityMode) throws HibernateException { // todo : this call will not work for anything other than pojos! ClassMetadata cm = factory.getClassMetadata( entity.getClass() ); if ( cm==null ) return entity.getClass().getName(); Map result = new HashMap(); if ( cm.hasIdentifierProperty() ) { result.put( cm.getIdentifierPropertyName(), cm.getIdentifierType().toLoggableString( cm.getIdentifier( entity, entityMode ), factory ) ); } Type[] types = cm.getPropertyTypes(); String[] names = cm.getPropertyNames(); Object[] values = cm.getPropertyValues( entity, entityMode ); for ( int i=0; i<types.length; i++ ) { if ( !names[i].startsWith("_") ) { String strValue = values[i]==LazyPropertyInitializer.UNFETCHED_PROPERTY ? values[i].toString() : types[i].toLoggableString( values[i], factory ); result.put( names[i], strValue ); } } return cm.getEntityName() + result.toString(); }
Example 13
Project: ix3 File: MetaDataImplHibernate.java View Source Code | 5 votes |
@Override public List<String> getNaturalKeyPropertiesName() { List<String> naturalKeyPropertiesName = new ArrayList<String>(); ClassMetadata classMetadata = getClassMetadata(); if (classMetadata == null) { return naturalKeyPropertiesName; } if (classMetadata.hasNaturalIdentifier()) { int[] positions = classMetadata.getNaturalIdentifierProperties(); String[] propertyNames = classMetadata.getPropertyNames(); for (int i = 0; i < positions.length; i++) { int position = positions[i]; String naturalKeyPropertyName = propertyNames[position]; naturalKeyPropertiesName.add(naturalKeyPropertyName); } } else { //Si no hay clave natural, la lista no tendrá ningún elemento } return naturalKeyPropertiesName; }
Example 14
Project: breeze.server.java File: RelationshipFixer.java View Source Code | 5 votes |
/** * Connect the related entities based on the foreign key values. * Note that this may cause related entities to be loaded from the DB if they are not already in the session. * @param entityInfo Entity that will be saved * @param meta Metadata about the entity type */ private void processRelationships(EntityInfo entityInfo, ClassMetadata meta) { addToGraph(entityInfo, null); // make sure every entity is in the graph String[] propNames = meta.getPropertyNames(); Type[] propTypes = meta.getPropertyTypes(); Type propType = meta.getIdentifierType(); if (propType != null) { processRelationship(meta.getIdentifierPropertyName(), propType, entityInfo, meta); } for (int i = 0; i < propNames.length; i++) { processRelationship(propNames[i], propTypes[i], entityInfo, meta); } }
Example 15
Project: open-cyclos File: HibernateQueryHandler.java View Source Code | 5 votes |
@SuppressWarnings("unchecked") public void resolveReferences(final Entity entity) { final ClassMetadata meta = getClassMetaData(entity); final String[] names = meta.getPropertyNames(); final Type[] types = meta.getPropertyTypes(); for (int i = 0; i < types.length; i++) { final Type type = types[i]; final String name = names[i]; if (type instanceof EntityType) { // Properties that are relationships to other entities Entity rel = PropertyHelper.get(entity, name); if (rel instanceof EntityReference) { rel = getHibernateTemplate().load(EntityHelper.getRealClass(rel), rel.getId()); PropertyHelper.set(entity, name, rel); } } else if (type instanceof CollectionType && !(type instanceof MapType)) { // Properties that are collections of other entities final Collection<?> current = PropertyHelper.get(entity, name); if (current != null && !(current instanceof PersistentCollection)) { // We must check that the collection is made of entities, since Hibernate supports collections os values boolean isEntityCollection = true; final Collection<Entity> resolved = ClassHelper.instantiate(current.getClass()); for (final Object object : current) { if (object != null && !(object instanceof Entity)) { isEntityCollection = false; break; } Entity e = (Entity) object; if (object instanceof EntityReference) { e = getHibernateTemplate().load(EntityHelper.getRealClass(e), e.getId()); } resolved.add(e); } if (isEntityCollection) { PropertyHelper.set(entity, name, resolved); } } } } }
Example 16
Project: common-security-module File: HibernateHelper.java View Source Code | 5 votes |
public static HashMap getAssociatedAttributes(String className) throws CSException { className = className.substring(0, className.indexOf(" - ")); HttpSession session = WebContextFactory.get().getHttpServletRequest().getSession(); if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { throw new CSException("Session Expired - Please Relogin!"); } SessionFactory sessionFactory = (SessionFactory) session.getAttribute(DisplayConstants.HIBERNATE_SESSIONFACTORY); HashMap map = new HashMap(); ClassMetadata classMetadata = sessionFactory.getClassMetadata(className); List propertiesList = new ArrayList(); String[] properties1 = classMetadata.getPropertyNames(); for(int count = 0;count<properties1.length; count++){ propertiesList.add(new String(properties1[count])); } propertiesList.add(new String(classMetadata.getIdentifierPropertyName())); Iterator propertiesIterator = propertiesList.iterator(); while(propertiesIterator.hasNext()){ String property = (String)propertiesIterator.next(); Type type = classMetadata.getPropertyType(property); if (!(type instanceof AssociationType)) { map.put(property+"-_-"+(type.getReturnedClass()).getName(),property); } } if (map.size() == 0) throw new CSException("No associated Classes Found!"); return map; }
Example 17
Project: geoxygene File: GeodatabaseHibernate.java View Source Code | 4 votes |
/** Renseigne l'attribut _metadataList. */ protected void initMetadata() { this.metadataList = new ArrayList<Metadata>(); Map<?, ?> allClassesMetadata = HibernateUtil.getSessionFactory().getAllClassMetadata(); for (Object key : allClassesMetadata.keySet()) { if (GeodatabaseHibernate.logger.isDebugEnabled()) { GeodatabaseHibernate.logger.debug("key = " + key); } ClassMetadata classMetadata = (ClassMetadata) allClassesMetadata.get(key); if (GeodatabaseHibernate.logger.isDebugEnabled()) { GeodatabaseHibernate.logger.debug("metadata = " + classMetadata); } String className = (classMetadata.getEntityName()); if (GeodatabaseHibernate.logger.isDebugEnabled()) { GeodatabaseHibernate.logger.debug("entity name = " + className); } Metadata metadataElt = new Metadata(); metadataElt.setClassName(className); String[] propertyNames = classMetadata.getPropertyNames(); if (GeodatabaseHibernate.logger.isDebugEnabled()) { for (int i = 0; i < propertyNames.length; i++) { GeodatabaseHibernate.logger.debug("property name " + i + " = " + propertyNames[i]); } } if (classMetadata instanceof AbstractEntityPersister) { metadataElt.setTableName(((AbstractEntityPersister) classMetadata).getRootTableName()); metadataElt.setIdFieldName(((AbstractEntityPersister) classMetadata).getIdentifierPropertyName()); metadataElt.setIdColumnName(((AbstractEntityPersister) classMetadata).getIdentifierColumnNames()[0]); // FIXME a revoir: aussi l'enveloppe, les srid, la dimension, et // d'autres... metadataElt.setGeomColumnName("geom"); if (GeodatabaseHibernate.logger.isDebugEnabled()) { GeodatabaseHibernate.logger.debug("table name = " + metadataElt.getTableName()); GeodatabaseHibernate.logger.debug("id field name = " + metadataElt.getIdFieldName()); GeodatabaseHibernate.logger.debug("id column name = " + metadataElt.getIdColumnName()); } } this.metadataList.add(metadataElt); } }
Example 18
Project: AlgoTrader File: GrailsHibernateDomainClass.java View Source Code | 4 votes |
/** * Contructor to be used by all child classes to create a new instance * and get the name right. * * @param clazz the Grails class * @param sessionFactory The Hibernate SessionFactory instance * @param metaData The ClassMetaData for this class retrieved from the SF * @param defaultConstraints The default global constraints definition */ public GrailsHibernateDomainClass(Class<?> clazz, SessionFactory sessionFactory, GrailsApplication application, ClassMetadata metaData, Map<String, Object> defaultConstraints) { super(clazz, ""); this.application = application; new StandardAnnotationMetadata(clazz); String ident = metaData.getIdentifierPropertyName(); this.defaultConstraints = defaultConstraints; if (ident != null) { Class<?> identType = getPropertyType(ident); this.identifier = new GrailsHibernateDomainClassProperty(this, ident); this.identifier.setIdentity(true); this.identifier.setType(identType); this.propertyMap.put(ident, this.identifier); } // configure the version property final int versionIndex = metaData.getVersionProperty(); String versionPropertyName = null; if (versionIndex > -1) { versionPropertyName = metaData.getPropertyNames()[versionIndex]; this.version = new GrailsHibernateDomainClassProperty(this, versionPropertyName); this.version.setType(getPropertyType(versionPropertyName)); } // configure remaining properties String[] propertyNames = metaData.getPropertyNames(); boolean[] propertyNullablility = metaData.getPropertyNullability(); for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; if (!propertyName.equals(ident) && !(versionPropertyName != null && propertyName.equals(versionPropertyName))) { GrailsHibernateDomainClassProperty prop = new GrailsHibernateDomainClassProperty(this, propertyName); prop.setType(getPropertyType(propertyName)); Type hibernateType = metaData.getPropertyType(propertyName); // if its an association type if (hibernateType.isAssociationType()) { prop.setAssociation(true); // get the associated type from the session factory and set it on the property AssociationType assType = (AssociationType) hibernateType; if (assType instanceof AnyType) { continue; } try { String associatedEntity = assType.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory); ClassMetadata associatedMetaData = sessionFactory.getClassMetadata(associatedEntity); prop.setRelatedClassType(associatedMetaData.getMappedClass(EntityMode.POJO)); } catch (MappingException me) { // other side must be a value object if (hibernateType.isCollectionType()) { prop.setRelatedClassType(Collection.class); } } // configure type of relationship if (hibernateType.isCollectionType()) { prop.setOneToMany(true); } else if (hibernateType.isEntityType()) { prop.setManyToOne(true); // might not really be true, but for our purposes this is ok prop.setOneToOne(true); } prop.setOptional(propertyNullablility[i]); } this.propertyMap.put(propertyName, prop); } } this.properties = this.propertyMap.values().toArray(new GrailsDomainClassProperty[this.propertyMap.size()]); // process the constraints evaluateConstraints(); }
Example 19
Project: common-security-module File: HibernateHelper.java View Source Code | 4 votes |
public static HashMap getAssociatedClasses(String className) throws CSException { System.out.println("className "+className); boolean isParentClass = false; HttpSession session = WebContextFactory.get().getHttpServletRequest().getSession(); if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { throw new CSException("Session Expired - Please Relogin!"); } if(className.contains(" - self")){ throw new CSException("No Associations allowed for direct security filter clause."); } SessionFactory sessionFactory = (SessionFactory) session.getAttribute(DisplayConstants.HIBERNATE_SESSIONFACTORY); HashMap map = new HashMap(); if (!(className.contains(" - "))) { isParentClass = true; } else { className = className.substring(0, className.indexOf(" - ")); } System.out.println("className2 "+className); ClassMetadata classMetadata = sessionFactory.getClassMetadata(className); String[] properties = classMetadata.getPropertyNames(); for (int i = 0 ; i < properties.length ; i++) { Type type = classMetadata.getPropertyType(properties[i]); if (type instanceof AssociationType) { try{ AssociationType associationType = (AssociationType)type; map.put(properties[i],associationType.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory) + " - " + properties[i]); }catch(Exception e){ throw new CSException("Hibernate Error: "+e.getMessage()); } } } System.out.println("isParentClass "+isParentClass); if (isParentClass) { map.put(className, className + " - self"); } if (map.size() == 0) throw new CSException("No associated Classes Found!"); System.out.println("map "+map); return map; }
Example 20
Project: openhds-server File: DDIController.java View Source Code | 4 votes |
public String buildDDIDocument() throws ClassNotFoundException { // a mapping of table names with their associated ClassMetaData Map<?, ?> mapping = genericDao.getClassMetaData(); // all table names Object[] keySet = mapping.keySet().toArray(); Properties props = new Properties(); props.put("studyName", studyDocument.getStudyName()); props.put("studyId", studyDocument.getStudyId()); props.put("studyStartDate", studyDocument.getStudyStartDate().toString()); props.put("affiliation", studyDocument.getAffiliation()); props.put("author", studyDocument.getAuthor()); props.put("email", studyDocument.getEmail()); props.put("version", appSettings.getVersionNumber()); props.put("notes", studyDocument.getNotes()); props.put("nation", studyDocument.getNationAbrv()); props.put("studyEndDate", studyDocument.getStudyEndDate().toString()); codeBookService.setMetadata(mapping); codeBookService.setProperties(props); codeBookService.createCodeBook(); codeBookService.buildDocumentDescription(); codeBookService.buildStudyDescription(); int count = 0; // iterate through all tables for (int i = 0; i < keySet.length; i++) { String tableName = (String) keySet[i]; // using reflection to get the entity Class<?> clazz = Class.forName(tableName); String classDesc = getDescription(clazz.getAnnotations()); // hibernate metadata associated with the table ClassMetadata data = (ClassMetadata) mapping.get(tableName); // all column names of the table String propertyNames[] = data.getPropertyNames(); // list of all fields for the entity ArrayList<Field> fieldsList = buildFieldList(clazz); // must iterate through all columns for (int j = 0; j < propertyNames.length; j++) { count++; // the column name String fieldName = propertyNames[j]; // annotations from the fieldName Annotation[] annotations = getAnnotationMatch(fieldName, fieldsList); // enumerated list List<?> enumList = getEnumeratedValues(fieldName, fieldsList); // description from annotation String desc = getDescription(annotations); String type; if (enumList != null) type = enumList.get(0).getClass().getName(); else type = data.getPropertyType(fieldName).getName(); String iteration = Integer.toString(count); codeBookService.buildFileDescription(tableName, classDesc, propertyNames, "jdbc:mysql://localhost/openhds"); codeBookService.buildDataDescription(tableName, fieldName, type, iteration, desc, enumList); } } return codeBookService.getDoc().toString(); }