Example #1
0
 private Object getEntityId(Object obj, HibernateTemplate ht)
     throws IllegalAccessException, InvocationTargetException {
   ClassMetadata cm = ht.getSessionFactory().getClassMetadata(superClass);
   String idCol = cm.getIdentifierPropertyName();
   PropertyDescriptor idPropDescr = BeanUtils.getPropertyDescriptor(superClass, idCol);
   return idPropDescr.getReadMethod().invoke(obj);
 }
 /**
  * Returns <code>true</code> if the entity name needs to be filtered.
  *
  * <p>Implementation filteres out inherited hibernate mappings, since the select query for the
  * base class will cover any inherited classes as well.
  *
  * <p>Note, that this method is called after it has been verified that the class has Compass
  * mappings (either directly, or indirectly by an interface or a super class).
  *
  * @param entityname The name of the entity
  * @param classMetadata The Hibernate class meta data.
  * @param device The Jpa Gps device
  * @return <code>true</code> if the entity should be filtered out, <code>false</code> if not.
  */
 protected boolean shouldFilter(
     String entityname, ClassMetadata classMetadata, Map allClassMetaData, JpaGpsDevice device) {
   Class<?> clazz = classMetadata.getMappedClass();
   // if it is inherited, do not add it to the classes to index, since the "from [entity]"
   // query for the base class will return results for this class as well
   if (classMetadata.isInherited()) {
     String superClassEntityName = ((AbstractEntityPersister) classMetadata).getMappedSuperclass();
     ClassMetadata superClassMetadata = (ClassMetadata) allClassMetaData.get(superClassEntityName);
     Class superClass = superClassMetadata.getMappedClass();
     // only filter out classes that their super class has compass mappings
     if (superClass != null
         && ((CompassGpsInterfaceDevice) device.getGps())
             .hasMappingForEntityForIndex(superClass)) {
       if (log.isDebugEnabled()) {
         log.debug(
             "Entity ["
                 + entityname
                 + "] is inherited and super class ["
                 + superClass
                 + "] has compass mapping, filtering it out");
       }
       return true;
     }
   }
   return false;
 }
    /**
     * Takes a class name as a string and find that class and all of its subclasses (transitively)
     * returns them as a list.
     */
    private static List<Class<?>> hierarchy(Map<String, ClassMetadata> m, String key) {

      final List<Class<?>> h = new ArrayList<Class<?>>();

      ClassMetadata cm = m.get(key);
      Class<?> c = cm.getMappedClass(EntityMode.POJO);
      h.add(c);

      int index = 0;

      while (index < h.size()) {
        for (String key2 : m.keySet()) {
          if (key.equals(key2)) {
            continue;
          } else {
            cm = m.get(key2);
            c = cm.getMappedClass(EntityMode.POJO);
            if (c.getSuperclass().equals(h.get(index))) {
              h.add(c);
            }
          }
        }
        index++;
      }
      return h;
    }
 /**
  * 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. {@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 #5
0
 /** 取得对象的主键名,辅助函数. */
 public String getIdName(Class<T> clazz) {
   Assert.notNull(clazz);
   ClassMetadata meta = getSessionFactory().getClassMetadata(clazz);
   Assert.notNull(meta, "Class " + clazz + " not define in hibernate session factory.");
   String idName = meta.getIdentifierPropertyName();
   Assert.hasText(idName, clazz.getSimpleName() + " has no identifier property define.");
   return idName;
 }
  /**
   * @param writer
   * @param includeHistory
   * @param session
   * @throws DataAccessException
   * @throws HibernateException
   */
  private void writeObjects(
      final Writer writer,
      final boolean includeHistory,
      final Session session,
      final boolean preserveIds)
      throws DataAccessException, HibernateException {
    // Container für die Objekte
    final List<Object> all = new ArrayList<Object>();
    final XStream stream = initXStream(session, true);
    final XStream defaultXStream = initXStream(session, false);

    session.flush();
    // Alles laden
    List<?> list = session.createQuery("select o from java.lang.Object o").setReadOnly(true).list();
    list = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
    final int size = list.size();
    log.info("Writing " + size + " objects");
    for (final Iterator<?> it = list.iterator(); it.hasNext(); ) {
      final Object obj = it.next();
      if (log.isDebugEnabled()) {
        log.debug("loaded object " + obj);
      }
      if ((obj instanceof HistoryEntry || obj instanceof PropertyDelta)
          && includeHistory == false) {
        continue;
      }
      Hibernate.initialize(obj);
      final Class<?> targetClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
      final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass);
      if (classMetadata == null) {
        log.fatal("Can't init " + obj + " of type " + targetClass);
        continue;
      }
      // initalisierung des Objekts...
      defaultXStream.marshal(obj, new CompactWriter(new NullWriter()));

      if (preserveIds == false) {
        // Nun kann die ID gelöscht werden
        classMetadata.setIdentifier(obj, null, EntityMode.POJO);
      }
      if (log.isDebugEnabled()) {
        log.debug("loading evicted object " + obj);
      }
      if (this.ignoreFromTopLevelListing.contains(targetClass) == false) {
        all.add(obj);
      }
    }
    // und schreiben
    try {
      writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
    } catch (final IOException ex) {
      // ignore, will fail on stream.marshal()
    }
    log.info("Wrote " + all.size() + " objects");
    final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy();
    stream.setMarshallingStrategy(marshallingStrategy);
    stream.marshal(all, new PrettyPrintWriter(writer));
  }
 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 #8
0
  public void initializeCollection(T instance, String collectionName) {
    ClassMetadata classMetadata = sessionFactory.getClassMetadata(instance.getClass());
    Object collection = classMetadata.getPropertyValue(instance, collectionName);

    if (!Hibernate.isInitialized(collection)) {
      attachClean(instance);
      Hibernate.initialize(collection);
    }
  }
Example #9
0
  /**
   * 取得对象的主键名,辅助函数.
   *
   * @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 #10
0
  public Pager findPager(Pager pager, Criteria criteria) {
    Assert.notNull(pager, "pager is required");
    Assert.notNull(criteria, "criteria is required");

    Integer pageNumber = pager.getPageNumber();
    Integer pageSize = pager.getPageSize();
    String searchBy = pager.getSearchBy();
    String keyword = pager.getKeyword();
    String orderBy = pager.getOrderBy();
    Pager.Order order = pager.getOrder();

    if (StringUtils.isNotEmpty(searchBy) && StringUtils.isNotEmpty(keyword)) {
      if (searchBy.contains(".")) {
        String alias = StringUtils.substringBefore(searchBy, ".");
        criteria.createAlias(alias, alias);
      }
      criteria.add(Restrictions.like(searchBy, "%" + keyword + "%"));
    }

    pager.setTotalCount(criteriaResultTotalCount(criteria));

    if (StringUtils.isNotEmpty(orderBy) && order != null) {
      if (order == Pager.Order.asc) {
        criteria.addOrder(Order.asc(orderBy));
      } else {
        criteria.addOrder(Order.desc(orderBy));
      }
    }

    ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
    if (!StringUtils.equals(orderBy, ORDER_LIST_PROPERTY_NAME)
        && ArrayUtils.contains(classMetadata.getPropertyNames(), ORDER_LIST_PROPERTY_NAME)) {
      criteria.addOrder(Order.asc(ORDER_LIST_PROPERTY_NAME));
      criteria.addOrder(Order.desc(CREATE_DATE_PROPERTY_NAME));
      if (StringUtils.isEmpty(orderBy) || order == null) {
        pager.setOrderBy(ORDER_LIST_PROPERTY_NAME);
        pager.setOrder(Pager.Order.asc);
      }
    } else if (!StringUtils.equals(orderBy, CREATE_DATE_PROPERTY_NAME)
        && ArrayUtils.contains(classMetadata.getPropertyNames(), CREATE_DATE_PROPERTY_NAME)) {
      criteria.addOrder(Order.desc(CREATE_DATE_PROPERTY_NAME));
      if (StringUtils.isEmpty(orderBy) || order == null) {
        pager.setOrderBy(CREATE_DATE_PROPERTY_NAME);
        pager.setOrder(Pager.Order.desc);
      }
    }

    criteria.setFirstResult((pageNumber - 1) * pageSize);
    criteria.setMaxResults(pageSize);

    pager.setResult(criteria.list());
    return pager;
  }
 private boolean copyState(Object entity, Type[] types, Object[] state, SessionFactory sf) {
   // copy the entity state into the state array and return true if the state has changed
   ClassMetadata metadata = sf.getClassMetadata(entity.getClass());
   Object[] newState = metadata.getPropertyValues(entity, EntityMode.POJO);
   int size = newState.length;
   boolean isDirty = false;
   for (int index = 0; index < size; index++) {
     if (!types[index].isEqual(state[index], newState[index], EntityMode.POJO)) {
       isDirty = true;
       state[index] = newState[index];
     }
   }
   return isDirty;
 }
 protected void setRelatedClassType(
     GrailsHibernateDomainClassProperty prop, AssociationType assType, Type hibernateType) {
   try {
     String associatedEntity =
         assType.getAssociatedEntityName((SessionFactoryImplementor) getSessionFactory());
     ClassMetadata associatedMetaData = getSessionFactory().getClassMetadata(associatedEntity);
     prop.setRelatedClassType(associatedMetaData.getMappedClass(EntityMode.POJO));
   } catch (MappingException me) {
     // other side must be a value object
     if (hibernateType.isCollectionType()) {
       prop.setRelatedClassType(Collection.class);
     }
   }
 }
    public IObject[] getLockCandidates(IObject o) {
      int idx = 0;
      IObject[] toCheck = new IObject[total()];
      Object[] values = cm.getPropertyValues(o, EntityMode.POJO);
      for (int i = 0; i < size(); i++) {
        if (!include(i)) {
          continue;
        }

        // this relation has subtypes and therefore is an embedded
        // component. This means that the value in values[] is the
        // instance itself. we will now have to acquire the actual
        // component values.
        if (hasSubtypes(i)) {
          for (int j = 0; j < numberOfSubtypes(i); j++) {
            Object value = getSubtypeValue(i, j, o);
            if (value != null) {
              toCheck[idx++] = (IObject) value;
            }
          }
        }

        // this is a regular relation. if the value is non null,
        // add it to the list of candidates.
        else if (values[i] != null) {
          toCheck[idx++] = (IObject) values[i];
        }
      }

      IObject[] retVal;
      retVal = new IObject[idx];
      System.arraycopy(toCheck, 0, retVal, 0, idx);
      return retVal;
    }
Example #14
0
 @SuppressWarnings("unchecked")
 public List<T> getAllList() {
   ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
   String hql;
   if (ArrayUtils.contains(classMetadata.getPropertyNames(), ORDER_LIST_PROPERTY_NAME)) {
     hql =
         "from "
             + entityClass.getName()
             + " as entity order by entity."
             + ORDER_LIST_PROPERTY_NAME
             + " desc";
   } else {
     hql = "from " + entityClass.getName();
   }
   return getSession().createQuery(hql).list();
 }
Example #15
0
 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();
   }
 }
    /**
     * examines all {@link Type types} for this class and stores pointers to those fields which
     * represent {@link IObject} instances. These fields may need to be locked when an object of
     * this type is created or updated.
     */
    Locks(ClassMetadata classMetadata) {

      this.cm = classMetadata;
      String[] name = cm.getPropertyNames();
      Type[] type = cm.getPropertyTypes();
      List<String[]> checks = new ArrayList<String[]>();
      List<String[]> groupChecks = new ArrayList<String[]>();

      this.size = type.length;
      this.include = new boolean[size];
      this.subnames = new String[size][];
      this.subtypes = new Type[size][];

      for (int i = 0; i < type.length; i++) {
        if (type[i].isComponentType() && ((ComponentType) type[i]).isEmbedded()) {
          EmbeddedComponentType embedded = (EmbeddedComponentType) type[i];
          String[] sub_name = embedded.getPropertyNames();
          Type[] sub_type = embedded.getSubtypes();
          List<String> name_list = new ArrayList<String>();
          List<Type> type_list = new ArrayList<Type>();
          for (int j = 0; j < sub_type.length; j++) {
            if (IObject.class.isAssignableFrom(sub_type[j].getReturnedClass())) {
              String path = name[i] + "." + sub_name[j];
              name_list.add(path);
              type_list.add(sub_type[j]);

              addCheck(checks, groupChecks, sub_type[j].getReturnedClass(), path);
            }
          }
          add(
              i,
              name_list.toArray(new String[name_list.size()]),
              type_list.toArray(new Type[type_list.size()]));
        } else if (IObject.class.isAssignableFrom(type[i].getReturnedClass())) {
          add(i);
          addCheck(checks, groupChecks, type[i].getReturnedClass(), name[i]);
          // Create checks for

        }
      }
      this.checks = checks.toArray(new String[checks.size()][]);
      this.groupChecks = groupChecks.toArray(new String[groupChecks.size()][]);
    }
Example #17
0
  @Override
  public void delete(long id) {
    String entityName = entityClassMetadata.getEntityName();
    String idPropertyName = entityClassMetadata.getIdentifierPropertyName();

    String hqlDeleteQuery =
        new StringBuffer()
            .append("delete ")
            .append(entityName)
            .append(" where ")
            .append(idPropertyName)
            .append(" = :id")
            .toString();

    Query deleteQuery = getCurrentSession().createQuery(hqlDeleteQuery);
    deleteQuery.setParameter("id", id);

    deleteQuery.executeUpdate();
  }
  private List<String> getCollectionRoles(
      final SessionFactory sessionFactory, final Class<?> entityClass) {
    List<String> collectionRoles = entityCollectionRoles.get(entityClass);
    if (collectionRoles != null) {
      return collectionRoles;
    }

    final com.google.common.collect.ImmutableList.Builder<String> collectionRolesBuilder =
        ImmutableList.builder();
    final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
    for (final Type type : classMetadata.getPropertyTypes()) {
      if (type.isCollectionType()) {
        collectionRolesBuilder.add(((CollectionType) type).getRole());
      }
    }

    collectionRoles = collectionRolesBuilder.build();
    entityCollectionRoles.put(entityClass, collectionRoles);

    return collectionRoles;
  }
  public EntityInformation[] locate(EntityManagerFactory entityManagerFactory, JpaGpsDevice device)
      throws JpaGpsDeviceException {

    CompassGpsInterfaceDevice gps = (CompassGpsInterfaceDevice) device.getGps();

    HibernateEntityManagerFactory hibernateEntityManagerFactory =
        (HibernateEntityManagerFactory) entityManagerFactory;
    SessionFactory sessionFactory = hibernateEntityManagerFactory.getSessionFactory();

    ArrayList<EntityInformation> entitiesList = new ArrayList<EntityInformation>();

    Map allClassMetaData = sessionFactory.getAllClassMetadata();
    for (Object o : allClassMetaData.keySet()) {
      String entityname = (String) o;
      if (!gps.hasMappingForEntityForIndex((entityname))) {
        if (log.isDebugEnabled()) {
          log.debug("Entity [" + entityname + "] does not have compass mapping, filtering it out");
        }
        continue;
      }

      ClassMetadata classMetadata = (ClassMetadata) allClassMetaData.get(entityname);
      if (shouldFilter(entityname, classMetadata, allClassMetaData, device)) {
        continue;
      }
      Class<?> clazz = classMetadata.getMappedClass();
      ResourceMapping resourceMapping = gps.getMappingForEntityForIndex(entityname);
      EntityInformation entityInformation =
          new EntityInformation(
              clazz,
              entityname,
              new HibernateJpaQueryProvider(clazz, entityname),
              resourceMapping.getSubIndexHash().getSubIndexes());
      entitiesList.add(entityInformation);
      if (log.isDebugEnabled()) {
        log.debug("Entity [" + entityname + "] will be indexed");
      }
    }
    return entitiesList.toArray(new EntityInformation[entitiesList.size()]);
  }
    /**
     * For each of the fields contained in this {@link Locks} object, parse out the type and the
     * field name and store those as the key and value in the "value" argument.
     */
    public void fillRelationships(SessionFactoryImplementor sfi, Map<String, Relationship> value) {

      final Type[] types = cm.getPropertyTypes();
      for (int t = 0; t < types.length; t++) {

        final Type type = types[t];
        final String name = type.getName();

        String to = null;
        Relationship field = null;
        if (type instanceof EntityType) {
          final EntityType entType = (EntityType) type;
          to = entType.getAssociatedEntityName();
          field = new Relationship(cm.getPropertyNames()[t], false);

        } else if (types[t] instanceof CollectionType) {
          final CollectionType colType = (CollectionType) types[t];
          final Type elemType = colType.getElementType(sfi);
          if (!elemType.isEntityType()) {
            continue; // The case for count maps and other primitives.
          }
          to = elemType.getName();

          int open = name.indexOf("(");
          int close = name.lastIndexOf(")");
          String role = name.substring(open + 1, close);
          int dot = role.lastIndexOf(".");
          field = new Relationship(role.substring(dot + 1), true);
        }

        if (to != null && field != null) {
          Map<String, ClassMetadata> m = sfi.getAllClassMetadata();
          for (Class<?> c : Impl.hierarchy(m, to)) {
            value.put(c.getName(), field);
          }
        }
      }
    }
Example #21
0
  public void /*test*/ AddNewProperty() {
    System.out.println("******************* testAddNewProperty ********************");
    PersistentClass userMapping = HibernateUtil.getClassMapping(User.class);

    Column column = new Column();
    column.setName("MOTTO");
    column.setNullable(false);
    column.setUnique(true);
    column.setSqlType("VARCHAR");
    userMapping.getTable().addColumn(column);

    SimpleValue value = new SimpleValue();
    value.setTable(userMapping.getTable());
    value.addColumn(column);
    value.setTypeName("string");

    Property prop = new Property();
    prop.setValue(value);
    prop.setName("motto");
    prop.setPropertyAccessorName("field");
    prop.setNodeName(prop.getName());
    userMapping.addProperty(prop);

    HibernateUtil.rebuildSessionFactory();

    ClassMetadata metadata = HibernateUtil.getClassMetadata(User.class);
    String[] propNames = metadata.getPropertyNames();
    boolean mottoFound = false;
    for (int i = 0; i < propNames.length; i++) {
      String propName = propNames[i];
      if (propName.equalsIgnoreCase("motto")) {
        mottoFound = true;
        break;
      }
    }

    assertTrue(mottoFound);
  }
    /**
     * examines all model objects to see which fields contain a {@link Type} which points to this
     * class. Uses {@link #locksFields(Type[])} since this is the inverse process.
     */
    private String[][] lockedByFields(String klass, Map<String, ClassMetadata> m) {
      if (m == null) {
        throw new InternalException("ClassMetadata map cannot be null.");
      }

      List<String[]> fields = new ArrayList<String[]>();

      for (String k : m.keySet()) {
        ClassMetadata cm = m.get(k);
        Type[] type = cm.getPropertyTypes();
        String[] names = cm.getPropertyNames();
        Locks inverse = locksHolder.get(k);
        for (int i = 0; i < inverse.size(); i++) {

          if (!inverse.include(i)) {
            continue;
          }

          // this is an embedded component and must be treated
          // specially. specifically, that we cannot compare against
          // the top-level returnedClass name but rather against
          // each of the individual subtype returnedClass names.
          if (inverse.hasSubtypes(i)) {
            for (int j = 0; j < inverse.numberOfSubtypes(i); j++) {
              if (inverse.subtypeEquals(i, j, klass)) {
                fields.add(new String[] {k, inverse.subtypeName(i, j)});
              }
            }
          }

          // no subtypes so can compare directly
          else if (klass.equals(type[i].getReturnedClass().getName())) {
            fields.add(new String[] {k, names[i]});
          }
        }
      }
      return fields.toArray(new String[fields.size()][2]);
    }
Example #23
0
  public boolean matches(String name, Object value) {
    boolean matches = false;

    EnvironmentImpl environment = EnvironmentImpl.getCurrent();
    if (environment != null) {
      SessionFactory sessionFactory = null;
      if (hibernateSessionFactoryName != null) {
        sessionFactory = (SessionFactory) environment.get(hibernateSessionFactoryName);
      } else {
        sessionFactory = environment.get(SessionFactory.class);
      }
      if (sessionFactory != null) {
        ClassMetadata classMetadata = sessionFactory.getClassMetadata(value.getClass());
        matches =
            ((classMetadata != null)
                && (classMetadata.getIdentifierType().getClass() == getIdType()));
      }
    } else {
      log.trace(
          "no current environment so valueClass cannot be stored as an id-ref to a hibernate object");
      matches = false;
    }
    return matches;
  }
  @Test
  public void entityMappingTest() {
    try {
      log.info("querying all the managed entities...");
      final Map<String, ClassMetadata> metadataMap =
          session.getSessionFactory().getAllClassMetadata();

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

        log.info("executing hql= " + query.getQueryString());

        for (Object o : query.list()) {
          log.info("IEntity=  " + o);
        }
      }
    } finally {
      session.flush();
    }
    log.info("성공했습니다.");
  }
Example #25
0
  private void addChildExampleCriteria(Object exampleInstance, Criteria criteria, Session sesion) {
    ClassMetadata metadata =
        sesion.getSessionFactory().getClassMetadata(exampleInstance.getClass());

    String[] propertyNames = metadata.getPropertyNames();
    Type[] propertyTypes = metadata.getPropertyTypes();

    // see if this example instance has any properties that are entities
    for (int i = 0; i < propertyNames.length; i++) {

      String propertyName = propertyNames[i];
      Type propertyType = propertyTypes[i];

      if (propertyType instanceof EntityType) {
        // this property is an association - Hibernate's Example ignores
        // these
        Object value = metadata.getPropertyValue(exampleInstance, propertyName, EntityMode.POJO);

        if (value != null) {

          ClassMetadata childMetadata =
              sesion.getSessionFactory().getClassMetadata(value.getClass());
          Criteria childCriteria = criteria.createCriteria(propertyName);

          if (childMetadata.hasIdentifierProperty()) {

            Object id = childMetadata.getIdentifier(value, EntityMode.POJO);
            if (id != null) {
              // add the identifier to the child criteria
              childCriteria.add(Restrictions.eq(childMetadata.getIdentifierPropertyName(), id));
            }
          }

          // add the entity's fields as Example fields
          childCriteria.add(Example.create(value));

          // add this entity's associations
          addChildExampleCriteria(value, childCriteria, sesion);
        }
      }
    } // ~for
  }
    Immutables(ClassMetadata metadata) {
      if (metadata instanceof EntityPersister) {
        this.ep = (EntityPersister) metadata;
      } else {
        throw new IllegalArgumentException(
            "Metadata passed to Immutables"
                + " must be an instanceof EntityPersister, not "
                + (metadata == null ? null : metadata.getClass()));
      }

      List<String> retVal = new ArrayList<String>();
      Type[] type = this.ep.getPropertyTypes();
      String[] name = this.ep.getPropertyNames();
      boolean[] up = this.ep.getPropertyUpdateability();

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

        // not updateable, so our work (for this type) is done.
        if (!up[i]) {
          retVal.add(name[i]);
        }

        // updateable, but maybe a component subtype is NOT.
        else if (type[i].isComponentType() && ((ComponentType) type[i]).isEmbedded()) {
          EmbeddedComponentType embedded = (EmbeddedComponentType) type[i];
          String[] sub_name = embedded.getPropertyNames();
          Type[] sub_type = embedded.getSubtypes();
          List<String> name_list = new ArrayList<String>();
          List<Type> type_list = new ArrayList<Type>();
          for (int j = 0; j < sub_type.length; j++) {
            // INCOMPLETE !!!
          }
        }
      }
      immutableFields = retVal.toArray(new String[retVal.size()]);
    }
 /** uses the {@link ClassMetadata} for this {@link Locks} tp retrieve the component value. */
 public Object getSubtypeValue(int i, int j, Object o) {
   return cm.getPropertyValue(o, subnames[i][j], EntityMode.POJO);
 }
Example #28
0
 /** 取得对象的主键名. */
 public String getIdName() {
   ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
   return meta.getIdentifierPropertyName();
 }
    /**
     * Initializes the metadata needed by this instance.
     *
     * @param sessionFactory
     * @see SessionFactory#getAllClassMetadata()
     */
    public void setSessionFactory(SessionFactory sessionFactory) {

      if (initialized) {
        return; // EARLY EXIT !!
      }

      log.info("Calculating ExtendedMetadata...");

      SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
      Map<String, ClassMetadata> m = sessionFactory.getAllClassMetadata();

      // do Locks() first because they are used during the
      // calculation of LockedBy()
      for (String key : m.keySet()) {
        ClassMetadata cm = m.get(key);
        locksHolder.put(key, new Locks(cm));
      }

      // now that all Locks() are available, determine LockedBy()
      for (String key : m.keySet()) {
        lockedByHolder.put(key, lockedByFields(key, m));
      }

      for (String key : m.keySet()) {
        ClassMetadata cm = m.get(key);
        immutablesHolder.put(key, new Immutables(cm));
      }

      for (Map.Entry<String, ClassMetadata> entry : m.entrySet()) {
        String key = entry.getKey();
        ClassMetadata cm = entry.getValue();
        key = key.substring(key.lastIndexOf(".") + 1).toLowerCase();
        if (hibernateClasses.containsKey(key)) {
          throw new RuntimeException("Duplicate keys!: " + key);
        }
        hibernateClasses.put(key, cm.getMappedClass(EntityMode.POJO));
      }

      for (String key : m.keySet()) {
        Map<String, Relationship> value = new HashMap<String, Relationship>();
        ClassMetadata cm = m.get(key);
        for (Class<?> c : hierarchy(m, key)) {
          Locks locks = locksHolder.get(c.getName());
          locks.fillRelationships(sfi, value);
        }

        // FIXME: using simple name rather than FQN
        Map<String, Relationship> value2 = new HashMap<String, Relationship>();
        for (Map.Entry<String, Relationship> i : value.entrySet()) {
          String k = i.getKey();
          k = k.substring(k.lastIndexOf(".") + 1);
          value2.put(k, i.getValue());
        }
        relationships.put(key.substring(key.lastIndexOf(".") + 1), value2);
      }

      Set<Class<IAnnotated>> anns = new HashSet<Class<IAnnotated>>();
      Set<Class<Annotation>> anns2 = new HashSet<Class<Annotation>>();
      for (String key : m.keySet()) {
        ClassMetadata cm = m.get(key);
        Map<String, String> queries = countQueriesAndEditTargets(key, lockedByHolder.get(key));
        collectionCountHolder.putAll(queries);

        // Checking classes, specifically for ITypes
        Class c = cm.getMappedClass(EntityMode.POJO);
        if (IAnnotated.class.isAssignableFrom(c)) {
          anns.add(c);
        }
        if (Annotation.class.isAssignableFrom(c)) {
          anns2.add(c);
        }
      }
      annotatableTypes.addAll(anns);
      annotationTypes.addAll(anns2);
      initialized = true;
    }
 /** 取得对象的主键名. */
 public String getIdName() {
   ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
   Assert.notNull(
       meta, "Class " + entityClass.getSimpleName() + " not define in HibernateSessionFactory.");
   return meta.getIdentifierPropertyName();
 }