Exemple #1
0
/* 247:    */   
/* 248:    */   static String buildSafeClassName(String className, String defaultPackageName)
/* 249:    */   {
/* 250:286 */     if ((className.indexOf('.') < 0) && (StringHelper.isNotEmpty(defaultPackageName))) {
/* 251:287 */       className = StringHelper.qualify(defaultPackageName, className);
/* 252:    */     }
/* 253:289 */     return className;
/* 254:    */   }
 public SelectFragment addColumn(String tableAlias, String columnName, String columnAlias) {
   columns.add(StringHelper.qualify(tableAlias, columnName));
   // columns.add(columnName);
   // aliases.add(tableAlias);
   columnAliases.add(columnAlias);
   return this;
 }
  public String toSubselectString(String ukname) {
    String[] joinColumns =
        ukname == null
            ? StringHelper.qualify(alias, loadable.getIdentifierColumnNames())
            : ((PropertyMapping) loadable).toColumns(alias, ukname);

    return "select " + StringHelper.join(", ", joinColumns) + queryString;
  }
 static String buildSafeClassName(String className, String defaultPackageName) {
   if (className != null
       && className.indexOf('.') < 0
       && StringHelper.isNotEmpty(defaultPackageName)) {
     className = StringHelper.qualify(defaultPackageName, className);
   }
   return className;
 }
  private SessionFactory buildSessionFactory() {
    // Extra options located in src/test/resources/hibernate.properties
    Properties envProps = Environment.getProperties();
    envProps.setProperty(Environment.DIALECT, "HSQL");
    envProps.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
    envProps.setProperty(
        Environment.CONNECTION_PROVIDER, JtaAwareConnectionProviderImpl.class.getName());
    envProps.setProperty(Environment.JNDI_CLASS, "org.jnp.interfaces.NamingContextFactory");
    envProps.setProperty(Environment.TRANSACTION_STRATEGY, "jta");
    envProps.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "jta");
    envProps.setProperty(Environment.RELEASE_CONNECTIONS, "auto");
    envProps.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
    envProps.setProperty(Environment.USE_QUERY_CACHE, "true");
    envProps.put(AvailableSettings.JTA_PLATFORM, new JBossStandAloneJtaPlatform());
    envProps.setProperty(
        Environment.CACHE_REGION_FACTORY,
        "org.hibernate.test.cache.infinispan.functional.SingleNodeTestCase$TestInfinispanRegionFactory");
    serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry(envProps);

    MetadataSources sources = new MetadataSources(serviceRegistry);

    String[] mappings =
        new String[] {"org/hibernate/test/cache/infinispan/functional/Item.hbm.xml"};
    for (String mapping : mappings) {
      sources.addResource(mapping);
    }
    Metadata metadata = sources.buildMetadata();
    Iterator<EntityBinding> entityIter = metadata.getEntityBindings().iterator();
    while (entityIter.hasNext()) {
      EntityBinding binding = entityIter.next();
      binding.getHierarchyDetails().getCaching().setAccessType(AccessType.TRANSACTIONAL);
      binding.getHierarchyDetails().getCaching().setRequested(TruthValue.TRUE);
      binding.getHierarchyDetails().getCaching().setRegion(binding.getEntityName());
      binding.getHierarchyDetails().getCaching().setCacheLazyProperties(true);
    }
    Iterator<PluralAttributeBinding> collectionIter = metadata.getCollectionBindings().iterator();
    while (collectionIter.hasNext()) {
      PluralAttributeBinding binding = collectionIter.next();
      binding.getCaching().setAccessType(AccessType.TRANSACTIONAL);
      binding.getCaching().setRequested(TruthValue.TRUE);
      binding
          .getCaching()
          .setRegion(
              StringHelper.qualify(
                  binding.getContainer().seekEntityBinding().getEntityName(),
                  binding.getAttribute().getName()));
      binding.getCaching().setCacheLazyProperties(true);
    }
    return metadata.buildSessionFactory();
  }
Exemple #6
0
 public static StringBuilder buildBatchFetchRestrictionFragment(
     String alias, String[] columnNames, Dialect dialect) {
   // the general idea here is to just insert a placeholder that we can easily find later...
   if (columnNames.length == 1) {
     // non-composite key
     return new StringBuilder(StringHelper.qualify(alias, columnNames[0]))
         .append(" in (")
         .append(BATCH_ID_PLACEHOLDER)
         .append(")");
   } else {
     // composite key - the form to use here depends on what the dialect supports.
     if (dialect.supportsRowValueConstructorSyntaxInInList()) {
       // use : (col1, col2) in ( (?,?), (?,?), ... )
       StringBuilder builder = new StringBuilder();
       builder.append("(");
       boolean firstPass = true;
       String deliminator = "";
       for (String columnName : columnNames) {
         builder.append(deliminator).append(StringHelper.qualify(alias, columnName));
         if (firstPass) {
           firstPass = false;
           deliminator = ",";
         }
       }
       builder.append(") in (");
       builder.append(BATCH_ID_PLACEHOLDER);
       builder.append(")");
       return builder;
     } else {
       // use : ( (col1 = ? and col2 = ?) or (col1 = ? and col2 = ?) or ... )
       //		unfortunately most of this building needs to be held off until we know
       //		the exact number of ids :(
       return new StringBuilder("(").append(BATCH_ID_PLACEHOLDER).append(")");
     }
   }
 }
  /** For a composite element, add to a list of associations to be fetched by outerjoin */
  private void walkCompositeElementTree(
      final CompositeType compositeType,
      final String[] cols,
      final QueryableCollection persister,
      final String alias,
      final PropertyPath path,
      final int currentDepth)
      throws MappingException {

    Type[] types = compositeType.getSubtypes();
    String[] propertyNames = compositeType.getPropertyNames();
    int begin = 0;
    for (int i = 0; i < types.length; i++) {
      int length = types[i].getColumnSpan(getFactory());
      String[] lhsColumns = ArrayHelper.slice(cols, begin, length);

      if (types[i].isAssociationType()) {
        AssociationType associationType = (AssociationType) types[i];

        // simple, because we can't have a one-to-one or a collection
        // (or even a property-ref) in a composite-element:
        String[] aliasedLhsColumns = StringHelper.qualify(alias, lhsColumns);

        final PropertyPath subPath = path.append(propertyNames[i]);
        final boolean[] propertyNullability = compositeType.getPropertyNullability();
        final JoinType joinType =
            getJoinType(
                associationType,
                compositeType.getFetchMode(i),
                subPath,
                persister.getTableName(),
                lhsColumns,
                propertyNullability == null || propertyNullability[i],
                currentDepth,
                compositeType.getCascadeStyle(i));
        addAssociationToJoinTreeIfNecessary(
            associationType, aliasedLhsColumns, alias, subPath, currentDepth, joinType);
      } else if (types[i].isComponentType()) {
        final PropertyPath subPath = path.append(propertyNames[i]);
        walkCompositeElementTree(
            (CompositeType) types[i], lhsColumns, persister, alias, subPath, currentDepth);
      }
      begin += length;
    }
  }
 public static Ejb3JoinColumn[] buildJoinColumnsWithDefaultColumnSuffix(
     JoinColumn[] anns,
     String mappedBy,
     Map<String, Join> joins,
     PropertyHolder propertyHolder,
     String propertyName,
     String suffixForDefaultColumnName,
     MetadataBuildingContext buildingContext) {
   JoinColumn[] actualColumns =
       propertyHolder.getOverriddenJoinColumn(
           StringHelper.qualify(propertyHolder.getPath(), propertyName));
   if (actualColumns == null) actualColumns = anns;
   if (actualColumns == null || actualColumns.length == 0) {
     return new Ejb3JoinColumn[] {
       buildJoinColumn(
           null,
           mappedBy,
           joins,
           propertyHolder,
           propertyName,
           suffixForDefaultColumnName,
           buildingContext)
     };
   } else {
     int size = actualColumns.length;
     Ejb3JoinColumn[] result = new Ejb3JoinColumn[size];
     for (int index = 0; index < size; index++) {
       result[index] =
           buildJoinColumn(
               actualColumns[index],
               mappedBy,
               joins,
               propertyHolder,
               propertyName,
               suffixForDefaultColumnName,
               buildingContext);
     }
     return result;
   }
 }
 @Override
 public String[] getIdentifierColumns(Criteria criteria) {
   String[] idcols =
       ((Loadable) getPropertyMapping(getEntityName(criteria))).getIdentifierColumnNames();
   return StringHelper.qualify(getSQLAlias(criteria), idcols);
 }
  // TODO refactor this code, there is a lot of duplication in this method
  public void doSecondPass(Map persistentClasses) throws MappingException {
    org.hibernate.mapping.OneToOne value =
        new org.hibernate.mapping.OneToOne(
            mappings, propertyHolder.getTable(), propertyHolder.getPersistentClass());
    final String propertyName = inferredData.getPropertyName();
    value.setPropertyName(propertyName);
    String referencedEntityName =
        ToOneBinder.getReferenceEntityName(inferredData, targetEntity, mappings);
    value.setReferencedEntityName(referencedEntityName);
    AnnotationBinder.defineFetchingStrategy(value, inferredData.getProperty());
    // value.setFetchMode( fetchMode );
    value.setCascadeDeleteEnabled(cascadeOnDelete);
    // value.setLazy( fetchMode != FetchMode.JOIN );

    if (!optional) value.setConstrained(true);
    value.setForeignKeyType(
        value.isConstrained()
            ? ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT
            : ForeignKeyDirection.FOREIGN_KEY_TO_PARENT);
    PropertyBinder binder = new PropertyBinder();
    binder.setName(propertyName);
    binder.setValue(value);
    binder.setCascade(cascadeStrategy);
    binder.setAccessType(inferredData.getDefaultAccess());
    Property prop = binder.makeProperty();
    if (BinderHelper.isEmptyAnnotationValue(mappedBy)) {
      /*
       * we need to check if the columns are in the right order
       * if not, then we need to create a many to one and formula
       * but actually, since entities linked by a one to one need
       * to share the same composite id class, this cannot happen in hibernate
       */
      boolean rightOrder = true;

      if (rightOrder) {
        String path = StringHelper.qualify(propertyHolder.getPath(), propertyName);
        (new ToOneFkSecondPass(
                value,
                joinColumns,
                !optional, // cannot have nullabe and unique on certain DBs
                propertyHolder.getEntityOwnerClassName(),
                path,
                mappings))
            .doSecondPass(persistentClasses);
        // no column associated since its a one to one
        propertyHolder.addProperty(prop, inferredData.getDeclaringClass());
      } else {
        // this is a many to one with Formula

      }
    } else {
      PersistentClass otherSide =
          (PersistentClass) persistentClasses.get(value.getReferencedEntityName());
      Property otherSideProperty;
      try {
        if (otherSide == null) {
          throw new MappingException("Unable to find entity: " + value.getReferencedEntityName());
        }
        otherSideProperty = BinderHelper.findPropertyByName(otherSide, mappedBy);
      } catch (MappingException e) {
        throw new AnnotationException(
            "Unknown mappedBy in: "
                + StringHelper.qualify(ownerEntity, ownerProperty)
                + ", referenced property unknown: "
                + StringHelper.qualify(value.getReferencedEntityName(), mappedBy));
      }
      if (otherSideProperty == null) {
        throw new AnnotationException(
            "Unknown mappedBy in: "
                + StringHelper.qualify(ownerEntity, ownerProperty)
                + ", referenced property unknown: "
                + StringHelper.qualify(value.getReferencedEntityName(), mappedBy));
      }
      if (otherSideProperty.getValue() instanceof OneToOne) {
        propertyHolder.addProperty(prop, inferredData.getDeclaringClass());
      } else if (otherSideProperty.getValue() instanceof ManyToOne) {
        Iterator it = otherSide.getJoinIterator();
        Join otherSideJoin = null;
        while (it.hasNext()) {
          Join otherSideJoinValue = (Join) it.next();
          if (otherSideJoinValue.containsProperty(otherSideProperty)) {
            otherSideJoin = otherSideJoinValue;
            break;
          }
        }
        if (otherSideJoin != null) {
          // @OneToOne @JoinTable
          Join mappedByJoin =
              buildJoinFromMappedBySide(
                  (PersistentClass) persistentClasses.get(ownerEntity),
                  otherSideProperty,
                  otherSideJoin);
          ManyToOne manyToOne = new ManyToOne(mappings, mappedByJoin.getTable());
          // FIXME use ignore not found here
          manyToOne.setIgnoreNotFound(ignoreNotFound);
          manyToOne.setCascadeDeleteEnabled(value.isCascadeDeleteEnabled());
          manyToOne.setEmbedded(value.isEmbedded());
          manyToOne.setFetchMode(value.getFetchMode());
          manyToOne.setLazy(value.isLazy());
          manyToOne.setReferencedEntityName(value.getReferencedEntityName());
          manyToOne.setUnwrapProxy(value.isUnwrapProxy());
          prop.setValue(manyToOne);
          Iterator otherSideJoinKeyColumns = otherSideJoin.getKey().getColumnIterator();
          while (otherSideJoinKeyColumns.hasNext()) {
            Column column = (Column) otherSideJoinKeyColumns.next();
            Column copy = new Column();
            copy.setLength(column.getLength());
            copy.setScale(column.getScale());
            copy.setValue(manyToOne);
            copy.setName(column.getQuotedName());
            copy.setNullable(column.isNullable());
            copy.setPrecision(column.getPrecision());
            copy.setUnique(column.isUnique());
            copy.setSqlType(column.getSqlType());
            copy.setCheckConstraint(column.getCheckConstraint());
            copy.setComment(column.getComment());
            copy.setDefaultValue(column.getDefaultValue());
            manyToOne.addColumn(copy);
          }
          mappedByJoin.addProperty(prop);
        } else {
          propertyHolder.addProperty(prop, inferredData.getDeclaringClass());
        }

        value.setReferencedPropertyName(mappedBy);

        String propertyRef = value.getReferencedPropertyName();
        if (propertyRef != null) {
          mappings.addUniquePropertyReference(value.getReferencedEntityName(), propertyRef);
        }
      } else {
        throw new AnnotationException(
            "Referenced property not a (One|Many)ToOne: "
                + StringHelper.qualify(otherSide.getEntityName(), mappedBy)
                + " in mappedBy of "
                + StringHelper.qualify(ownerEntity, ownerProperty));
      }
    }
    ForeignKey fk = inferredData.getProperty().getAnnotation(ForeignKey.class);
    String fkName = fk != null ? fk.name() : "";
    if (!BinderHelper.isEmptyAnnotationValue(fkName)) value.setForeignKeyName(fkName);
  }