Java 类org.hibernate.metadata.ClassMetadata 实例源码

项目:lemon    文件:HibernateBasicDao.java   
/**
 * 取得对象的主键名,辅助函数.
 * 
 * @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;
}
项目:second-opinion-api    文件:TruncateDatabaseService.java   
@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();
}
项目:UniqueValidator    文件:UniqueValidator.java   
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;
}
项目:UniqueValidator    文件:UniqueValidator.java   
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;
}
项目:mycore    文件:MCRHibernateConfigHelper.java   
private static void modifyConstraints(SessionFactoryImpl sessionFactoryImpl) {
    ClassMetadata classMetadata = sessionFactoryImpl.getClassMetadata(MCRCategoryImpl.class);
    AbstractEntityPersister aep = (AbstractEntityPersister) classMetadata;
    String qualifiedTableName = aep.getTableName();
    try (Session session = sessionFactoryImpl.openSession()) {
        session.doWork(connection -> {
            String updateStmt = Stream.of("ClassLeftUnique", "ClassRightUnique")
                .flatMap(idx -> Stream.of("drop constraint if exists " + idx,
                    MessageFormat.format(
                        "add constraint {0} unique ({1}) deferrable initially deferred",
                        idx, getUniqueColumns(MCRCategoryImpl.class, idx))))
                .collect(Collectors.joining(", ", getAlterTableString(connection) + qualifiedTableName + " ", ""));
            try (Statement stmt = connection.createStatement()) {
                LogManager.getLogger().info("Fixing PostgreSQL Schema for {}:\n{}", qualifiedTableName, updateStmt);
                stmt.execute(updateStmt);
            }
        });
    }
}
项目:engerek    文件:RUtil.java   
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);
        }
    }
}
项目:ssh    文件:Main.java   
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();
    }
}
项目:dorset-framework    文件:HibernateServiceTest.java   
@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());
}
项目:dachs    文件:HibernateLazyIdExtractor.java   
@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;
    }
}
项目:singular-server    文件:HealthSystemDbService.java   
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);
}
项目:metaworks_framework    文件:DynamicDaoHelperImpl.java   
@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;
}
项目:xap-openspaces    文件:StatelessHibernateExternalDataSource.java   
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;
    }
}
项目:xap-openspaces    文件:CriteriaHibernateExternalDataSource.java   
/**
 * 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;
}
项目:xap-openspaces    文件:CriteriaHibernateExternalDataSource.java   
/**
 * 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;
}
项目:SparkCommerce    文件:DynamicDaoHelperImpl.java   
@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;
}
项目:jeecms6    文件:HibernateBaseDao.java   
/**
 * 将更新对象拷贝至实体对象,并处理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);
        }
    }
}
项目:scheduling    文件:TestJobRemove.java   
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();
    }
}
项目:elide    文件:InjectionAwareHibernateStore.java   
@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.");
    }
}
项目:Lucee4    文件:CFCGetter.java   
@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);
    }
}
项目:Lucee4    文件:HibernateUtil.java   
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;
    }
}
项目:Lucee4    文件:HibernateUtil.java   
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;
    }
}
项目:dorset-framework    文件:HibernateServiceTest.java   
@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());
}
项目:blcdemo    文件:DynamicDaoHelperImpl.java   
@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;
}
项目:lucas    文件:DBConnectionUtil.java   
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();
        }
    }
项目:First-Dash-Service    文件:Main.java   
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();
    }
}
项目:hql-builder    文件:HqlServiceImpl.java   
@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));
}
项目:midpoint    文件:RUtil.java   
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);
        }
    }
}
项目:openeos    文件:HibernateAnnotationsMixedDictionaryService.java   
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);

}
项目:ix3    文件:MetaDataFactoryImplHibernate.java   
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;
}
项目:ix3    文件:MetaDataImplHibernate.java   
@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;
    }
}
项目:haloDao-Hibernate3    文件:HaloDao.java   
/**
 * 取自锐道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;
}
项目:haloDao-Hibernate3    文件:HaloDao.java   
/**
 * 根据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();
}
项目:breeze.server.java    文件:RelationshipFixer.java   
/**
 * 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);
    }
}
项目:breeze.server.java    文件:RelationshipFixer.java   
/**
 * 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;
}
项目:breeze.server.java    文件:RelationshipFixer.java   
/**
 * 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;
}
项目:breeze.server.java    文件:HibernateSaveProcessor.java   
/**
 * 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);
    }
}
项目:breeze.server.java    文件:HibernateSaveProcessor.java   
/**
 * 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);
    }
}
项目:spacewalk    文件:HibernateFactory.java   
/**
 * 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);
}
项目:opennmszh    文件:AbstractDaoHibernate.java   
/**
 * <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();
    }
}
项目:midpoint    文件:RUtil.java   
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);
        }
    }
}