Java Code Examples for org.hibernate.metadata.ClassMetadata

The following are top voted examples for showing how to use org.hibernate.metadata.ClassMetadata. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: engerek   File: RUtil.java   Source Code and License 7 votes vote down vote up
private static void fixCompositeIdentifierInMetaModel(SessionFactory sessionFactory, Class clazz) {
    ClassMetadata classMetadata = sessionFactory.getClassMetadata(clazz);
    if (classMetadata instanceof AbstractEntityPersister) {
        AbstractEntityPersister persister = (AbstractEntityPersister) classMetadata;
        EntityMetamodel model = persister.getEntityMetamodel();
        IdentifierProperty identifier = model.getIdentifierProperty();

        try {
            Field field = IdentifierProperty.class.getDeclaredField("hasIdentifierMapper");
            field.setAccessible(true);
            field.set(identifier, true);
            field.setAccessible(false);
        } catch (Exception ex) {
            throw new SystemException("Attempt to fix entity meta model with hack failed, reason: "
                    + ex.getMessage(), ex);
        }
    }
}
 
Example 2
Project: dorset-framework   File: HibernateServiceTest.java   Source Code and License 7 votes vote down vote up
@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 3
Project: lemon   File: HibernateBasicDao.java   Source Code and License 6 votes vote down vote up
/**
 * 取得对象的主键名,辅助函数.
 * 
 * @param entityClass
 *            实体类型
 * @return 主键名称
 */
public String getIdName(Class entityClass) {
    Assert.notNull(entityClass);
    entityClass = ReflectUtils.getOriginalClass(entityClass);

    ClassMetadata meta = this.getSessionFactory().getClassMetadata(
            entityClass);
    Assert.notNull(meta, "Class " + entityClass
            + " not define in hibernate session factory.");

    String idName = meta.getIdentifierPropertyName();
    Assert.hasText(idName, entityClass.getSimpleName()
            + " has no identifier property define.");

    return idName;
}
 
Example 4
Project: second-opinion-api   File: TruncateDatabaseService.java   Source Code and License 6 votes vote down vote up
@Transactional
public void truncate() throws Exception {
	List<String> tableNames = new ArrayList<>();
	Session session = entityManager.unwrap(Session.class);
	Map<String, ClassMetadata> hibernateMetadata = session.getSessionFactory().getAllClassMetadata();

	for (ClassMetadata classMetadata : hibernateMetadata.values()) {
		AbstractEntityPersister aep = (AbstractEntityPersister) classMetadata;
		tableNames.add(aep.getTableName());
	}

	entityManager.flush();
	entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
	tableNames.forEach(tableName -> entityManager.createNativeQuery("TRUNCATE TABLE " + tableName).executeUpdate());
	entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY TRUE").executeUpdate();
}
 
Example 5
Project: UniqueValidator   File: UniqueValidator.java   Source Code and License 6 votes vote down vote up
private boolean _hasRecord(Object value, Map<String, Object> fieldMap, String idName, Serializable idValue, ClassMetadata meta){
    DetachedCriteria criteria = DetachedCriteria
            .forClass(value.getClass())
            .setProjection(Projections.rowCount());

    for(Map.Entry<String, Object> fieldEntry: fieldMap.entrySet()){
        criteria.add(Restrictions.eq(fieldEntry.getKey(), fieldEntry.getValue()));
    }

    if(idValue != null){
        criteria.add(Restrictions.ne(idName, idValue));
    }

    Number count = (Number)criteria
            .getExecutableCriteria(getTmpSession())
            .list().iterator().next();

    return count.intValue() > 0;
}
 
Example 6
Project: UniqueValidator   File: UniqueValidator.java   Source Code and License 6 votes vote down vote up
private TreeMap<String, Object> _countRows(Object value) {
    ClassMetadata meta = getSessionFactory().getClassMetadata(value.getClass());
    String idName = meta.getIdentifierPropertyName();
    Serializable idValue = meta.getIdentifier(value, (SessionImplementor)getTmpSession());

    ArrayList<String[]> fieldSets;
    if(this._fields.length > 0){
        fieldSets = _prepareFields();
    }else{
        fieldSets = _getFieldsFromUniqueConstraint(value);
        fieldSets.addAll(_extractFieldsFromObject(value));
    }

    for(String[] fieldSet : fieldSets){
        TreeMap<String, Object> fieldMap = new TreeMap<>();
        for(String fieldName: fieldSet){
            fieldMap.put(fieldName, meta.getPropertyValue(value, fieldName));
        }
        if(_hasRecord(value, fieldMap, idName, idValue, meta)){
            return fieldMap;
        }
    }

    return null;
}
 
Example 7
Project: ssh   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Session session = getSession();
    try {
        System.out.println("querying all the managed entities...");
        final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
        for (Object key : metadataMap.keySet()) {
            final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
            final String entityName = classMetadata.getEntityName();
            final Query query = session.createQuery("from " + entityName);
            System.out.println("executing: " + query.getQueryString());
            for (Object o : query.list()) {
                System.out.println("  " + o);
            }
        }
    } finally {
        session.close();
    }
}
 
Example 8
Project: dachs   File: HibernateLazyIdExtractor.java   Source Code and License 6 votes vote down vote up
@Override
public String[] extractIdPropertyNames(Object entity)
{
    final IdClass idClassAnn = entity.getClass().getAnnotation(IdClass.class);
    if (idClassAnn != null)
    {
        final Class<?> entityClass = idClassAnn.value();
        final List<String> retVal = new ArrayList<>(3);
        ReflectionUtils.doWithFields(entityClass, (f)->
           {
               if (! Modifier.isStatic(f.getModifiers()))
               {
                   retVal.add(f.getName());
               }
           });
        return retVal.toArray(new String[retVal.size()]);
    }
    else
    {
        final ClassMetadata classMetadata = factory.getClassMetadata(entity.getClass());
        final String propertyName = classMetadata.getIdentifierPropertyName();
        return propertyName != null ? new String[]{propertyName} : null;
    }
}
 
Example 9
Project: singular-server   File: HealthSystemDbService.java   Source Code and License 6 votes vote down vote up
public HealthInfoDTO getAllDbMetaData() {
    List<TableInfoDTO> tables = new ArrayList<>();
    try {
        Map<String, ClassMetadata> map = saudeDao.getAllDbMetaData();
        map.forEach((k, v) -> tables.add(getTableInfo((AbstractEntityPersister) v)));

        Optional<IValidatorDatabase> validator = verificaDialetoUtilizado();
        if (validator.isPresent()) {
            validator.get().checkAllInfoTable(tables);
        }
    } catch (Exception e) {
        getLogger().error(e.getMessage(), e);
        tables.clear();
    }
    return new HealthInfoDTO(tables);
}
 
Example 10
Project: metaworks_framework   File: DynamicDaoHelperImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, Object> getIdMetadata(Class<?> entityClass, HibernateEntityManager entityManager) {
    Map<String, Object> response = new HashMap<String, Object>();
    SessionFactory sessionFactory = entityManager.getSession().getSessionFactory();
    
    ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass);
    if (metadata == null) {
        return null;
    }
    
    String idProperty = metadata.getIdentifierPropertyName();
    response.put("name", idProperty);
    Type idType = metadata.getIdentifierType();
    response.put("type", idType);

    return response;
}
 
Example 11
Project: xap-openspaces   File: StatelessHibernateExternalDataSource.java   Source Code and License 6 votes vote down vote up
protected boolean exists(BulkItem bulkItem, StatelessSession session) {
    
    Criteria criteria = null;
    switch (bulkItem.getOperation()) {
        case BulkItem.REMOVE:
        case BulkItem.WRITE:
        case BulkItem.UPDATE:
            Object entry = bulkItem.getItem();
            criteria = session.createCriteria(entry.getClass().getName());
            ClassMetadata classMetaData = getSessionFactory().getClassMetadata(entry.getClass());
            criteria.add(Restrictions.idEq(classMetaData.getIdentifier(entry)));
            criteria.setProjection(Projections.rowCount());
            return ((Number) criteria.uniqueResult()).intValue() > 0;
        case BulkItem.PARTIAL_UPDATE:
            criteria = session.createCriteria(bulkItem.getTypeName());
            criteria.add(Restrictions.idEq(bulkItem.getIdPropertyValue()));
            criteria.setProjection(Projections.rowCount());
            return ((Number) criteria.uniqueResult()).intValue() > 0;
       default:
            return false;
    }
}
 
Example 12
Project: xap-openspaces   File: CriteriaHibernateExternalDataSource.java   Source Code and License 6 votes vote down vote up
/**
 * Return pojo identifier
 */
protected Object getId(Object template) {
    Object id = null;

    ClassMetadata classMetaData = getMetadata(template);

    if (classMetaData == null) //Unexpected class entity
        return null;

    if (template instanceof IGSEntry) {
        id = ((IGSEntry) template).getFieldValue(classMetaData.getIdentifierPropertyName());
    } else {
        id = classMetaData.getIdentifier(template);
    }

    return id;
}
 
Example 13
Project: xap-openspaces   File: CriteriaHibernateExternalDataSource.java   Source Code and License 6 votes vote down vote up
/**
 * Return pojo entry metadata
 */
protected ClassMetadata getMetadata(Object entry) {
    String pojoName = null;
    if (entry instanceof IGSEntry)
        pojoName = ((IGSEntry) entry).getClassName();
    else
        pojoName = entry.getClass().getName();

    ClassMetadata entryClassMetadata = metaDataTable.get(pojoName);
    if (entryClassMetadata == null) {
        entryClassMetadata = getSessionFactory().getClassMetadata(pojoName);
        if (entryClassMetadata != null)
            metaDataTable.put(pojoName, entryClassMetadata);
    }
    return entryClassMetadata;
}
 
Example 14
Project: SparkCommerce   File: DynamicDaoHelperImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, Object> getIdMetadata(Class<?> entityClass, HibernateEntityManager entityManager) {
    Map<String, Object> response = new HashMap<String, Object>();
    SessionFactory sessionFactory = entityManager.getSession().getSessionFactory();
    
    ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass);
    if (metadata == null) {
        return null;
    }
    
    String idProperty = metadata.getIdentifierPropertyName();
    response.put("name", idProperty);
    Type idType = metadata.getIdentifierType();
    response.put("type", idType);

    return response;
}
 
Example 15
Project: jeecms6   File: HibernateBaseDao.java   Source Code and License 6 votes vote down vote up
/**
 * 将更新对象拷贝至实体对象,并处理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 16
Project: scheduling   File: TestJobRemove.java   Source Code and License 6 votes vote down vote up
private void checkAllEntitiesDeleted(String... skipClasses) {
    Set<String> skip = ImmutableSet.copyOf(skipClasses);

    Session session = dbManager.getSessionFactory().openSession();
    try {
        for (ClassMetadata metadata : session.getSessionFactory().getAllClassMetadata().values()) {
            if (!skip.contains(metadata.getEntityName())) {
                System.out.println("Check " + metadata.getEntityName());
                List<Object> list = session.createCriteria(metadata.getEntityName()).list();
                Assert.assertEquals("Unexpected " + metadata.getEntityName(), 0, list.size());
            }
        }
    } finally {
        session.close();
    }
}
 
Example 17
Project: elide   File: InjectionAwareHibernateStore.java   Source Code and License 6 votes vote down vote up
@Override
public void populateEntityDictionary(EntityDictionary dictionary) {
    // Bind all entities
    super.populateEntityDictionary(dictionary);

    if (injector != null) {
        log.info("Binding injector to entities");
        Collection<ClassMetadata> metadata = this.sessionFactory.getAllClassMetadata().values();
        log.info("Found {} entities", metadata.size());
        /* bind all entities to injector */
        metadata.forEach(meta -> {
            // Ensure they receive proper injection:
            dictionary.bindInitializer(injector::inject, meta.getMappedClass());
            log.debug("Elide bound entity: {}", meta.getEntityName());
        });
    } else {
        log.info("No injector found, not binding one to entities.");
    }
}
 
Example 18
Project: Lucee4   File: CFCGetter.java   Source Code and License 6 votes vote down vote up
@Override
public Object get(Object trg) throws HibernateException {
	try {
		// MUST cache this, perhaps when building xml
		PageContext pc = CommonUtil.pc();
		ORMSession session = ORMUtil.getSession(pc);
		Component cfc = CommonUtil.toComponent(trg);
		String dsn = ORMUtil.getDataSourceName(pc, cfc);
		String name = HibernateCaster.getEntityName(cfc);
		SessionFactory sf=(SessionFactory) session.getRawSessionFactory(dsn);
		ClassMetadata metaData = sf.getClassMetadata(name);
		Type type = HibernateUtil.getPropertyType(metaData, key.getString());

		Object rtn = cfc.getComponentScope().get(key,null);
		return HibernateCaster.toSQL(type, rtn,null);
	} 
	catch (PageException pe) {
		throw new HibernatePageException(pe);
	}
}
 
Example 19
Project: Lucee4   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
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 20
Project: Lucee4   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
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 21
Project: dorset-framework   File: HibernateServiceTest.java   Source Code and License 6 votes vote down vote up
@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 22
Project: blcdemo   File: DynamicDaoHelperImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, Object> getIdMetadata(Class<?> entityClass, HibernateEntityManager entityManager) {
    entityClass = getNonProxyImplementationClassIfNecessary(entityClass);
    Map<String, Object> response = new HashMap<String, Object>();
    SessionFactory sessionFactory = entityManager.getSession().getSessionFactory();
    
    ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass);
    if (metadata == null) {
        return null;
    }
    
    String idProperty = metadata.getIdentifierPropertyName();
    response.put("name", idProperty);
    Type idType = metadata.getIdentifierType();
    response.put("type", idType);

    return response;
}
 
Example 23
Project: lucas   File: DBConnectionUtil.java   Source Code and License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
        final Session session = getSession();
        try {
            System.out.println("querying all the managed entity...");
            final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
            for (Object key : metadataMap.keySet()) {
                final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
                final String entityName = classMetadata.getEntityName();
                for (Object o : getQuery("from " + entityName)) {
                    System.out.println("  " + o);
                }
//                for (Object o : getData(entityName)) {
//                    System.out.println("  " + o);
//                }
            }

        } finally {
            session.close();
        }
    }
 
Example 24
Project: First-Dash-Service   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Session session = getSession();
    try {
        System.out.println("querying all the managed entities...");
        final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
        for (Object key : metadataMap.keySet()) {
            final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
            final String entityName = classMetadata.getEntityName();
            final Query query = session.createQuery("from " + entityName);
            System.out.println("executing: " + query.getQueryString());
            for (Object o : query.list()) {
                System.out.println("  " + o);
            }
        }
    } finally {
        session.close();
    }
}
 
Example 25
Project: hql-builder   File: HqlServiceImpl.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends Serializable, I extends Serializable> T get(Class<T> type, I id) {
    Object idv = id;
    String name = type.getName();
    ClassMetadata classMetadata = (ClassMetadata) new MetadataResolver().getAllClassMetadata(sessionFactory).get(name);
    String oid = classMetadata.getIdentifierPropertyName();
    if (id instanceof String) {
        IdentifierType<?> identifierType = (IdentifierType<?>) classMetadata.getIdentifierType();
        if (!(identifierType instanceof StringType)) {
            try {
                idv = identifierType.stringToObject((String) id);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    QueryParameters hql = new QueryParameters("from " + name + " where " + oid + "=:" + oid,
            new QueryParameter().setName(oid).setValueTypeText(idv));
    logger.debug("hql={}", hql);
    List<Serializable> value = execute(hql).getResults().getValue();
    return (T) (value.isEmpty() ? null : value.get(0));
}
 
Example 26
Project: midpoint   File: RUtil.java   Source Code and License 6 votes vote down vote up
private static void fixCompositeIdentifierInMetaModel(SessionFactory sessionFactory, Class clazz) {
    ClassMetadata classMetadata = sessionFactory.getClassMetadata(clazz);
    if (classMetadata instanceof AbstractEntityPersister) {
        AbstractEntityPersister persister = (AbstractEntityPersister) classMetadata;
        EntityMetamodel model = persister.getEntityMetamodel();
        IdentifierProperty identifier = model.getIdentifierProperty();

        try {
            Field field = IdentifierProperty.class.getDeclaredField("hasIdentifierMapper");
            field.setAccessible(true);
            field.set(identifier, true);
            field.setAccessible(false);
        } catch (Exception ex) {
            throw new SystemException("Attempt to fix entity meta model with hack failed, reason: "
                    + ex.getMessage(), ex);
        }
    }
}
 
Example 27
Project: openeos   File: HibernateAnnotationsMixedDictionaryService.java   Source Code and License 6 votes vote down vote up
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 28
Project: ix3   File: MetaDataFactoryImplHibernate.java   Source Code and License 6 votes vote down vote up
private ClassMetadata getClassMetadata(String entityName) {
    Map<String,ClassMetadata> classMetadatas=sessionFactory.getAllClassMetadata();
    ClassMetadata classMetadata=null;


    for(String fqcn:classMetadatas.keySet()) {
        if (fqcn.endsWith("."+entityName) || (fqcn.equals(entityName))) {

            if (classMetadata!=null) {
                throw new RuntimeException("Existen 2 entidades con el mismo nombre:"+ fqcn + " y " + classMetadata.getEntityName() + " para la solicitud de " + entityName);
            }

            classMetadata=classMetadatas.get(fqcn);
        }
    }

    return classMetadata;
}
 
Example 29
Project: ix3   File: MetaDataImplHibernate.java   Source Code and License 6 votes vote down vote up
@Override
public es.logongas.ix3.dao.metadata.CollectionType getCollectionType() {
    ClassMetadata classMetadata = getClassMetadata();
    if (classMetadata == null) {
        throw new RuntimeException("No existen los metadatos");
    }

    if (type instanceof SetType) {
        return es.logongas.ix3.dao.metadata.CollectionType.Set;
    } else if (type instanceof ListType) {
        return es.logongas.ix3.dao.metadata.CollectionType.List;
    } else if (type instanceof MapType) {
        return es.logongas.ix3.dao.metadata.CollectionType.Map;
    } else {
        return null;
    }
}
 
Example 30
Project: haloDao-Hibernate3   File: HaloDao.java   Source Code and License 6 votes vote down vote up
/**
 * 取自锐道hibernateUtil类 获取类型 包含关联的
 * 
 * @param property
 * @param classMetadata
 * @param sessionFactory
 * @return Type
 */
private Type getHibernateType(String property, ClassMetadata classMetadata, SessionFactory sessionFactory) {
	String[] tokens = StringUtils.split(property, '.');
	if (tokens.length == 1)
		return classMetadata.getPropertyType(property);
	if (tokens.length > 1) {
		Type type = null;
		ClassMetadata meta = classMetadata;
		for (String token : tokens) {
			type = meta.getPropertyType(token);
			if ((type instanceof EntityType)) {

				EntityType entityType = (EntityType) type;
				String entityName = entityType.getAssociatedEntityName();
				meta = sessionFactory.getClassMetadata(entityName);

			}
		}
		return type;
	}
	return null;
}
 
Example 31
Project: haloDao-Hibernate3   File: HaloDao.java   Source Code and License 6 votes vote down vote up
/**
 * 根据HaloMap删除
 * 
 * @param parameter
 * @return 返回行数 失败返回-1
 */
public final int deleteByMap(HaloMap parameter) {
	if(null==parameter){
		parameter= new HaloMap();
	}
	ClassMetadata cm = sessionFactory.getClassMetadata(this.entityType);
	String entityName = cm.getEntityName();
	String selectHql = String.format("delete %s ", entityName);
	HqlWithParameter hqlWithParameter = createQueryHql(parameter, selectHql);
	String hql = hqlWithParameter.getHql();
	HaloMap hqlPrmMap = hqlWithParameter.getParamterMap();
	if (hqlPrmMap.isEmpty()) {
		logger.warn("不允许无条件删除!防止全表更新(可通过条件实现)");
		return -1;
	}
	Query query = createQuery(hql, hqlPrmMap);
	return query.executeUpdate();
}
 
Example 32
Project: breeze.server.java   File: RelationshipFixer.java   Source Code and License 6 votes vote down vote up
/**
 * Set an association value based on the value of the foreign key.  This updates the property of the entity.
 * @param propName Name of the navigation/association property of the entity, e.g. "Customer".  May be null if the property is the entity's identifier.
 * @param propType Type of the property
 * @param entityInfo Breeze EntityInfo
 * @param meta Metadata for the entity class
 */
private void fixupRelationship(String propName, EntityType propType, EntityInfo entityInfo, ClassMetadata meta)
{
    Object entity = entityInfo.entity;
    if (removeMode) {
        meta.setPropertyValue(entity, propName, null);
        return;
    }
    Object relatedEntity = getPropertyValue(meta, entity, propName);
    if (relatedEntity != null) {
        // entities are already connected - still need to add to dependency graph
        EntityInfo relatedEntityInfo = saveWorkState.findEntityInfo(relatedEntity);
        maybeAddToGraph(entityInfo, relatedEntityInfo, propType); 
        return;
    }

    relatedEntity = getRelatedEntity(propName, propType, entityInfo, meta);

    if (relatedEntity != null) {
        meta.setPropertyValue(entity, propName, relatedEntity);
    }
}
 
Example 33
Project: breeze.server.java   File: RelationshipFixer.java   Source Code and License 6 votes vote down vote up
/**
 * Get a related entity based on the value of the foreign key.  Attempts to find the related entity in the
 * saveMap; if its not found there, it is loaded via the Session (which should create a proxy, not actually load
 * the entity from the database).
 * Related entities are Promoted in the saveOrder according to their state.
 * @param propName Name of the navigation/association property of the entity, e.g. "Customer".  May be null if the property is the entity's identifier.
 * @param propType Type of the property
 * @param entityInfo Breeze EntityInfo
 * @param meta Metadata for the entity class
 * @return
 */
private Object getRelatedEntity(String propName, EntityType propType, EntityInfo entityInfo, ClassMetadata meta) {
    Object relatedEntity = null;
    String foreignKeyName = findForeignKey(propName, meta);
    Object id = getForeignKeyValue(entityInfo, meta, foreignKeyName);

    if (id != null) {
        Class returnEntityClass = propType.getReturnedClass();
        EntityInfo relatedEntityInfo = saveWorkState.findEntityInfoById(returnEntityClass, id);

        if (relatedEntityInfo == null) {
            EntityState state = entityInfo.entityState;
            //            	if (state == EntityState.Added || state == EntityState.Modified || (state == EntityState.Deleted 
            //            			&& propType.getForeignKeyDirection() != ForeignKeyDirection.FOREIGN_KEY_TO_PARENT)) {
            if (state != EntityState.Deleted || propType.getForeignKeyDirection() != ForeignKeyDirection.FOREIGN_KEY_TO_PARENT) {
                String relatedEntityName = propType.getName();
                relatedEntity = session.load(relatedEntityName, (Serializable) id, LockOptions.NONE);
            }
        } else {
            maybeAddToGraph(entityInfo, relatedEntityInfo, propType);
            relatedEntity = relatedEntityInfo.entity;
        }
    }
    return relatedEntity;
}
 
Example 34
Project: breeze.server.java   File: RelationshipFixer.java   Source Code and License 6 votes vote down vote up
/**
 * Get the value of the foreign key property.  This comes from the entity, but if that value is
 * null, and the entity is deleted, we try to get it from the originalValuesMap.
 * @param entityInfo Breeze EntityInfo
 * @param meta Metadata for the entity class
 * @param foreignKeyName Name of the foreign key property of the entity, e.g. "CustomerID"
 * @return
 */
private Object getForeignKeyValue(EntityInfo entityInfo, ClassMetadata meta, String foreignKeyName) {
    Object entity = entityInfo.entity;
    Object id = null;
    if (foreignKeyName.equalsIgnoreCase(meta.getIdentifierPropertyName())) {
        id = meta.getIdentifier(entity, null);
    } else if (Arrays.asList(meta.getPropertyNames()).contains(foreignKeyName)) {
        id = meta.getPropertyValue(entity, foreignKeyName);
    } else if (meta.getIdentifierType().isComponentType()) {
        // compound key
        ComponentType compType = (ComponentType) meta.getIdentifierType();
        int index = Arrays.asList(compType.getPropertyNames()).indexOf(foreignKeyName);
        if (index >= 0) {
            Object idComp = meta.getIdentifier(entity, null);
            id = compType.getPropertyValue(idComp, index, EntityMode.POJO);
        }
    }

    if (id == null && entityInfo.entityState == EntityState.Deleted) {
        id = entityInfo.originalValuesMap.get(foreignKeyName);
    }
    return id;
}
 
Example 35
Project: breeze.server.java   File: HibernateSaveProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * Add, update, or delete the entity according to its EntityState.
 * @param entityInfo
 * @param classMeta
 */
protected void processEntity(EntityInfo entityInfo) {
    Object entity = entityInfo.entity;
    ClassMetadata classMeta = getClassMetadata(entity.getClass());
    EntityState state = entityInfo.entityState;

    // Restore the old value of the concurrency column so Hibernate will be able to save the entity
    if (classMeta.isVersioned()) {
        restoreOldVersionValue(entityInfo, classMeta);
    }

    if (state == EntityState.Modified) {
        _session.update(entity);
    } else if (state == EntityState.Added) {
        _session.save(entity);
    } else if (state == EntityState.Deleted) {
        _session.delete(entity);
    } else {
        // Ignore EntityState.Unchanged.  Too many problems using session.Lock or session.Merge
        //session.Lock(entity, LockMode.None);
    }
}
 
Example 36
Project: breeze.server.java   File: HibernateSaveProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * 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 37
Project: spacewalk   File: HibernateFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Util to reload an object using Hibernate
 * @param obj to be reloaded
 * @return Object found if not, null
 * @throws HibernateException if something bad happens.
 */
public static Object reload(Object obj) throws HibernateException {
    // assertNotNull(obj);
    ClassMetadata cmd = connectionManager.getMetadata(obj);
    Serializable id = cmd.getIdentifier(obj, EntityMode.POJO);
    Session session = getSession();
    session.flush();
    session.evict(obj);
    /*
     * In hibernate 3, the following doesn't work:
     * session.load(obj.getClass(), id);
     * load returns the proxy class instead of the persisted class, ie,
     * Filter$$EnhancerByCGLIB$$9bcc734d_2 instead of Filter.
     * session.get is set to not return the proxy class, so that is what we'll use.
     */
    // assertNotSame(obj, result);
    return session.get(obj.getClass(), id);
}
 
Example 38
Project: opennmszh   File: AbstractDaoHibernate.java   Source Code and License 6 votes vote down vote up
/**
 * <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.getCause().getClass().getName().equals(PSQLException.class.getName())) {
        if (cause.getMessage().contains("duplicate key value violates unique constraint")) {
        	final ClassMetadata meta = getSessionFactory().getClassMetadata(m_entityClass);
            LogUtils.warnf(this, "Duplicate key constraint violation, class: %s, key value: %s", m_entityClass.getName(), meta.getPropertyValue(entity, meta.getIdentifierPropertyName(), EntityMode.POJO));
            break;
        } else if (cause.getMessage().contains("given object has a null identifier")) {
            LogUtils.warnf(this, "Null identifier on object, class: %s: %s", m_entityClass.getName(), entity.toString());
            break;
        }
        //}
        cause = cause.getCause();
    }
}
 
Example 39
Project: midpoint   File: RUtil.java   Source Code and License 6 votes vote down vote up
private static void fixCompositeIdentifierInMetaModel(SessionFactory sessionFactory, Class clazz) {
    ClassMetadata classMetadata = sessionFactory.getClassMetadata(clazz);
    if (classMetadata instanceof AbstractEntityPersister) {
        AbstractEntityPersister persister = (AbstractEntityPersister) classMetadata;
        EntityMetamodel model = persister.getEntityMetamodel();
        IdentifierProperty identifier = model.getIdentifierProperty();

        try {
            Field field = IdentifierProperty.class.getDeclaredField("hasIdentifierMapper");
            field.setAccessible(true);
            field.set(identifier, true);
            field.setAccessible(false);
        } catch (Exception ex) {
            throw new SystemException("Attempt to fix entity meta model with hack failed, reason: "
                    + ex.getMessage(), ex);
        }
    }
}
 
Example 40
Project: brewninja   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Print all data that is held in this database
 *
 * @throws org.hibernate.HibernateException
 */
public static void printAllData() throws HibernateException {
	Session session = getSession();

	try {
		System.out.println("querying all the managed entities...");

		final Map<String, ClassMetadata> metadataMap = session.getSessionFactory().getAllClassMetadata();

		for (String key : metadataMap.keySet()) {
			final ClassMetadata classMetadata = metadataMap.get(key);
			final String entityName = classMetadata.getEntityName();
			final Query query = session.createQuery("from " + entityName);

			System.out.println("executing: " + query.getQueryString());
			for (Object o : query.list()) {
				System.out.println("  " + o);
			}
		}

	} finally {
		session.close();
	}
}
 
Example 41
Project: open-cyclos   File: HibernateQueryHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Copies the persistent properties from the source to the destination entity
 */
public void copyProperties(final Entity source, final Entity dest) {
    if (source == null || dest == null) {
        return;
    }
    final ClassMetadata metaData = getClassMetaData(source);
    final Object[] values = metaData.getPropertyValues(source, EntityMode.POJO);
    // Skip the collections
    final Type[] types = metaData.getPropertyTypes();
    for (int i = 0; i < types.length; i++) {
        final Type type = types[i];
        if (type instanceof CollectionType) {
            values[i] = null;
        }
    }
    metaData.setPropertyValues(dest, values, EntityMode.POJO);
}
 
Example 42
Project: Lottery   File: HibernateBaseDao.java   Source Code and License 6 votes vote down vote up
/**
 * 将更新对象拷贝至实体对象,并处理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 43
Project: debop4j   File: SearchTool.java   Source Code and License 6 votes vote down vote up
/**
 * 인덱싱된 엔티티의 수형을 반환합니다.
 *
 * @param sessionFactory the session factory
 * @return 인덱싱된 엔티티의 수형들
 */
public static Set<Class> getIndexedClasses(SessionFactory sessionFactory) {
    if (log.isDebugEnabled())
        log.debug("매핑된 엔티티중에 인덱싱을 수행할 엔티티들을 조회합니다.");

    final Set<Class> classes = Sets.newHashSet();
    Collection<ClassMetadata> metadatas = sessionFactory.getAllClassMetadata().values();

    for (ClassMetadata meta : metadatas) {
        Class clazz = meta.getMappedClass();
        if (clazz.getAnnotation(Indexed.class) != null) {
            classes.add(clazz);

                log.trace("인덱싱된 엔티티=[{}]", clazz);
        }
    }
    return classes;
}
 
Example 44
Project: geomajas-project-server   File: HibernateEntityMapper.java   Source Code and License 6 votes vote down vote up
@Override
public EntityCollection getChildCollection(String name) throws LayerException {
	Type type = metadata.getPropertyType(name);
	if (type instanceof CollectionType) {
		CollectionType ct = (CollectionType) type;
		Collection coll = (Collection) metadata.getPropertyValue(object, name, EntityMode.POJO);
		if (coll == null) {
			// normally should not happen, hibernate instantiates it automatically
			coll = (Collection) ct.instantiate(0);
			metadata.setPropertyValue(object, name, coll, EntityMode.POJO);
		}
		String entityName = ct.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
		ClassMetadata childMetadata = sessionFactory.getClassMetadata(entityName);
		return new HibernateEntityCollection(metadata, childMetadata, object, coll);
	} else {
		throw new LayerException(ExceptionCode.FEATURE_MODEL_PROBLEM);
	}
}
 
Example 45
Project: geomajas-project-server   File: HibernateEntityMapper.java   Source Code and License 6 votes vote down vote up
/**
 * 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 46
Project: geomajas-project-server   File: InheritanceFeatureModelTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetAttribute() throws LayerException {
	ClassMetadata metadata = factory.getClassMetadata(AbstractHibernateTestFeature.class);
	Attribute<?> attribute = featureModel.getAttribute(feature1, PARAM_INT_ATTR);
	Assert.assertNotNull(attribute);
	Assert.assertTrue(attribute instanceof IntegerAttribute);
	Assert.assertEquals(feature1.getIntAttr(), attribute.getValue());

	attribute = featureModel.getAttribute(feature1, PARAM_TEXT_ATTR);
	Assert.assertNotNull(attribute);
	Assert.assertTrue(attribute instanceof StringAttribute);
	Assert.assertEquals(feature1.getTextAttr(), attribute.getValue());

	attribute = featureModel.getAttribute(feature1, ATTR__MANY_TO_ONE__DOT__INT);
	Assert.assertNotNull(attribute);
	Assert.assertTrue(attribute instanceof IntegerAttribute);
	Assert.assertEquals(feature1.getManyToOne().getIntAttr(), attribute.getValue());

	attribute = featureModel.getAttribute(feature1, ATTR__MANY_TO_ONE__DOT__TEXT);
	Assert.assertNotNull(attribute);
	Assert.assertTrue(attribute instanceof StringAttribute);
	Assert.assertEquals(feature1.getManyToOne().getTextAttr(), attribute.getValue());

	// attribute = featureModel.getAttribute(feature1, PARAM_ONE_TO_MANY + HibernateLayerUtil.SEPARATOR
	// + PARAM_INT_ATTR + "[0]");
}
 
Example 47
Project: OpenNMS   File: AbstractDaoHibernate.java   Source Code and License 6 votes vote down vote up
/**
 * <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.getCause().getClass().getName().equals(PSQLException.class.getName())) {
        if (cause.getMessage().contains("duplicate key value violates unique constraint")) {
        	final ClassMetadata meta = getSessionFactory().getClassMetadata(m_entityClass);
            LogUtils.warnf(this, "Duplicate key constraint violation, class: %s, key value: %s", m_entityClass.getName(), meta.getPropertyValue(entity, meta.getIdentifierPropertyName(), EntityMode.POJO));
            break;
        } else if (cause.getMessage().contains("given object has a null identifier")) {
            LogUtils.warnf(this, "Null identifier on object, class: %s: %s", m_entityClass.getName(), entity.toString());
            break;
        }
        //}
        cause = cause.getCause();
    }
}
 
Example 48
Project: gitplex-mit   File: DefaultIdManager.java   Source Code and License 5 votes vote down vote up
@Sessional
@Override
public void init() {
	for (ClassMetadata metadata: persistManager.getSessionFactory().getAllClassMetadata().values()) {
		Class<?> entityClass = metadata.getMappedClass();
		nextIds.put(entityClass, new AtomicLong(getMaxId(entityClass)+1));
	}
}
 
Example 49
Project: ctsms   File: QueryUtil.java   Source Code and License 5 votes vote down vote up
private static String getPropertyColumnName(Class entity, String property, SessionFactory sessionFactory) {
	ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(entity);
	AbstractEntityPersister persister = (AbstractEntityPersister) hibernateMetadata;
	String[] columnNames = persister.getPropertyColumnNames(property);
	return columnNames[0];
}
 
Example 50
Project: helium   File: EntityManagerFactoryImpl.java   Source Code and License 5 votes vote down vote up
public Object getIdentifier(Object entity) {
	final Class entityClass = Hibernate.getClass( entity );
	final ClassMetadata classMetadata = emf.getSessionFactory().getClassMetadata( entityClass );
	if (classMetadata == null) {
		throw new IllegalArgumentException( entityClass + " is not an entity" );
	}
	//TODO does that work for @IdClass?
	return classMetadata.getIdentifier( entity, EntityMode.POJO );
}
 
Example 51
Project: abixen-platform   File: DatabaseH2ServiceImpl.java   Source Code and License 5 votes vote down vote up
private void loadSystemTableList(SessionFactory sessionFactory) {
    Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata();
    allClassMetadata.forEach((key, value) -> {
        AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) value;
        SYSTEM_TABLE_LIST.add(abstractEntityPersister.getTableName());
    });
}
 
Example 52
Project: bamboobsc   File: DataUtils.java   Source Code and License 5 votes vote down vote up
public List<String> getEntityNameList(Session session) throws Exception {		
	Map<String, ClassMetadata> classMetadataMap = getClassMetadata(session);
	List<String> names = new ArrayList<String>();
	for (Map.Entry<String, ClassMetadata> entry : classMetadataMap.entrySet()) {
		names.add(entry.getValue().getEntityName());
	}		
	return names;
}
 
Example 53
Project: metaworks_framework   File: DynamicDaoHelperImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<String> getPropertyNames(Class<?> entityClass, HibernateEntityManager entityManager) {
    ClassMetadata metadata = getSessionFactory(entityManager).getClassMetadata(entityClass);
    List<String> propertyNames = new ArrayList<String>();
    Collections.addAll(propertyNames, metadata.getPropertyNames());
    return propertyNames;
}
 
Example 54
Project: metaworks_framework   File: DynamicDaoHelperImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<Type> getPropertyTypes(Class<?> entityClass, HibernateEntityManager entityManager) {
    ClassMetadata metadata = getSessionFactory(entityManager).getClassMetadata(entityClass);
    List<Type> propertyTypes = new ArrayList<Type>();
    Collections.addAll(propertyTypes, metadata.getPropertyTypes());
    return propertyTypes;
}
 
Example 55
Project: xap-openspaces   File: AbstractHibernateSpaceSynchronizationEndpoint.java   Source Code and License 5 votes vote down vote up
/**
 * 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 56
Project: xap-openspaces   File: StatelessHibernateSpaceSynchronizationEndpoint.java   Source Code and License 5 votes vote down vote up
private boolean exists(DataSyncOperation dataSyncOperation, StatelessSession session) {
    
    Criteria criteria = null;
    switch (dataSyncOperation.getDataSyncOperationType()) {
        case REMOVE:
        case WRITE:
        case UPDATE:
            if (!dataSyncOperation.supportsDataAsObject())
                return false;
            Object entry = dataSyncOperation.getDataAsObject();
            criteria = session.createCriteria(entry.getClass().getName());
            ClassMetadata classMetaData = getSessionFactory().getClassMetadata(entry.getClass());
            criteria.add(Restrictions.idEq(classMetaData.getIdentifier(entry)));
            criteria.setProjection(Projections.rowCount());
            return ((Number) criteria.uniqueResult()).intValue() > 0;
        case PARTIAL_UPDATE:
            if (!dataSyncOperation.supportsGetTypeDescriptor())
                return false;
            SpaceTypeDescriptor typeDescriptor = dataSyncOperation.getTypeDescriptor();
            criteria = session.createCriteria(typeDescriptor.getTypeName());
            criteria.add(Restrictions.idEq(typeDescriptor.getIdPropertyName()));
            criteria.setProjection(Projections.rowCount());
            return ((Number) criteria.uniqueResult()).intValue() > 0;
       default:
            return false;
    }
}
 
Example 57
Project: xap-openspaces   File: ManagedEntitiesContainer.java   Source Code and License 5 votes vote down vote up
private static Set<String> createManagedEntries(Set<String> managedEntries, SessionFactory sessionFactory) {
    if (managedEntries == null) {
        managedEntries = new HashSet<String>();
        // try and derive the managedEntries
        Map<String, ClassMetadata> allClassMetaData = sessionFactory.getAllClassMetadata();
        for (String entityname : allClassMetaData.keySet()) {
            managedEntries.add(entityname);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Using Hibernate managedEntries [" + managedEntries + "]");
    }
    return managedEntries;
}
 
Example 58
Project: xap-openspaces   File: AbstractHibernateExternalDataSource.java   Source Code and License 5 votes vote down vote up
/**
 * 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 59
Project: cacheonix-core   File: Printer.java   Source Code and License 5 votes vote down vote up
/**
 * @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 60
Project: SparkCommerce   File: DynamicDaoHelperImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<String> getPropertyNames(Class<?> entityClass, HibernateEntityManager entityManager) {
    ClassMetadata metadata = getSessionFactory(entityManager).getClassMetadata(entityClass);
    List<String> propertyNames = new ArrayList<String>();
    Collections.addAll(propertyNames, metadata.getPropertyNames());
    return propertyNames;
}