private AnnotationInstance overrideSchemaCatalogByDefault(
     AnnotationInstance annotationInstance, EntityMappingsMocker.Default defaults) {
   List<AnnotationValue> newAnnotationValueList = new ArrayList<AnnotationValue>();
   newAnnotationValueList.addAll(annotationInstance.values());
   boolean schemaDefined = false;
   boolean catalogDefined = false;
   if (annotationInstance.value("schema") != null) {
     schemaDefined = true;
   }
   if (annotationInstance.value("catalog") != null) {
     catalogDefined = true;
   }
   if (schemaDefined && catalogDefined) {
     return annotationInstance;
   }
   if (!catalogDefined && StringHelper.isNotEmpty(defaults.getCatalog())) {
     newAnnotationValueList.add(
         AnnotationValue.createStringValue("catalog", defaults.getCatalog()));
   }
   if (!schemaDefined && StringHelper.isNotEmpty(defaults.getSchema())) {
     newAnnotationValueList.add(AnnotationValue.createStringValue("schema", defaults.getSchema()));
   }
   return MockHelper.create(
       annotationInstance.name(),
       annotationInstance.target(),
       MockHelper.toArray(newAnnotationValueList));
 }
  private Map buildSettings() {
    Map settings = getConfig();
    addMappings(settings);

    if (createSchema()) {
      settings.put(org.hibernate.cfg.AvailableSettings.HBM2DDL_AUTO, "create-drop");
      final String secondSchemaName = createSecondSchema();
      if (StringHelper.isNotEmpty(secondSchemaName)) {
        if (!(getDialect() instanceof H2Dialect)) {
          throw new UnsupportedOperationException(
              "Only H2 dialect supports creation of second schema.");
        }
        Helper.createH2Schema(secondSchemaName, settings);
      }
    }

    if (StringHelper.isNotEmpty(getAuditStrategy())) {
      settings.put(EnversSettings.AUDIT_STRATEGY, getAuditStrategy());
    }

    if (!autoRegisterListeners()) {
      settings.put(EnversIntegrator.AUTO_REGISTER, "false");
    }

    settings.put(EnversSettings.USE_REVISION_ENTITY_WITH_NATIVE_ID, "false");

    settings.put(org.hibernate.cfg.AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
    settings.put(org.hibernate.cfg.AvailableSettings.DIALECT, getDialect().getClass().getName());
    return settings;
  }
Example #3
0
 private String createAttributePath(String prefix, String name) {
   String path = "";
   if (StringHelper.isNotEmpty(prefix)) {
     path += prefix;
   }
   if (StringHelper.isNotEmpty(path) && !path.endsWith(PROPERTY_PATH_SEPARATOR)) {
     path += PROPERTY_PATH_SEPARATOR;
   }
   path += name;
   return path;
 }
Example #4
0
  public static List<RelationalValueSource> buildValueSources(
      ValueSourcesAdapter valueSourcesAdapter, LocalBindingContext bindingContext) {
    List<RelationalValueSource> result = new ArrayList<RelationalValueSource>();

    if (StringHelper.isNotEmpty(valueSourcesAdapter.getColumnAttribute())) {
      if (valueSourcesAdapter.getColumnOrFormulaElements() != null
          && !valueSourcesAdapter.getColumnOrFormulaElements().isEmpty()) {
        throw new org.hibernate.metamodel.source.MappingException(
            "column/formula attribute may not be used together with <column>/<formula> subelement",
            bindingContext.getOrigin());
      }
      if (StringHelper.isNotEmpty(valueSourcesAdapter.getFormulaAttribute())) {
        throw new org.hibernate.metamodel.source.MappingException(
            "column and formula attributes may not be used together", bindingContext.getOrigin());
      }
      result.add(
          new ColumnAttributeSourceImpl(
              valueSourcesAdapter.getContainingTableName(),
              valueSourcesAdapter.getColumnAttribute(),
              valueSourcesAdapter.isIncludedInInsertByDefault(),
              valueSourcesAdapter.isIncludedInUpdateByDefault(),
              valueSourcesAdapter.isForceNotNull()));
    } else if (StringHelper.isNotEmpty(valueSourcesAdapter.getFormulaAttribute())) {
      if (valueSourcesAdapter.getColumnOrFormulaElements() != null
          && !valueSourcesAdapter.getColumnOrFormulaElements().isEmpty()) {
        throw new org.hibernate.metamodel.source.MappingException(
            "column/formula attribute may not be used together with <column>/<formula> subelement",
            bindingContext.getOrigin());
      }
      // column/formula attribute combo checked already
      result.add(
          new FormulaImpl(
              valueSourcesAdapter.getContainingTableName(),
              valueSourcesAdapter.getFormulaAttribute()));
    } else if (valueSourcesAdapter.getColumnOrFormulaElements() != null
        && !valueSourcesAdapter.getColumnOrFormulaElements().isEmpty()) {
      for (Object columnOrFormulaElement : valueSourcesAdapter.getColumnOrFormulaElements()) {
        if (JaxbColumnElement.class.isInstance(columnOrFormulaElement)) {
          result.add(
              new ColumnSourceImpl(
                  valueSourcesAdapter.getContainingTableName(),
                  (JaxbColumnElement) columnOrFormulaElement,
                  valueSourcesAdapter.isIncludedInInsertByDefault(),
                  valueSourcesAdapter.isIncludedInUpdateByDefault(),
                  valueSourcesAdapter.isForceNotNull()));
        } else {
          result.add(
              new FormulaImpl(
                  valueSourcesAdapter.getContainingTableName(), (String) columnOrFormulaElement));
        }
      }
    }
    return result;
  }
  private Ignore buildIgnore(String reason, String comment, String jiraKey) {
    StringBuilder buffer = new StringBuilder(reason);
    if (StringHelper.isNotEmpty(comment)) {
      buffer.append("; ").append(comment);
    }

    if (StringHelper.isNotEmpty(jiraKey)) {
      buffer.append(" (").append(jiraKey).append(')');
    }

    return new IgnoreImpl(buffer.toString());
  }
 private void applyNamedAttributeNodes(
     NamedAttributeNode[] namedAttributeNodes,
     NamedEntityGraph namedEntityGraph,
     AbstractGraphNode graphNode) {
   for (NamedAttributeNode namedAttributeNode : namedAttributeNodes) {
     if (StringHelper.isNotEmpty(namedAttributeNode.subgraph())) {
       final SubgraphImpl subgraph = graphNode.addSubgraph(namedAttributeNode.value());
       applyNamedSubgraphs(namedEntityGraph, namedAttributeNode.subgraph(), subgraph);
     }
     if (StringHelper.isNotEmpty(namedAttributeNode.keySubgraph())) {
       final SubgraphImpl subgraph = graphNode.addKeySubgraph(namedAttributeNode.value());
       applyNamedSubgraphs(namedEntityGraph, namedAttributeNode.keySubgraph(), subgraph);
     }
   }
 }
Example #7
0
/* 148:    */   
/* 149:    */   private static AnnotationValue enumValue(String name, DotName typeName, Enum value)
/* 150:    */   {
/* 151:182 */     if ((value != null) && (StringHelper.isNotEmpty(value.toString()))) {
/* 152:183 */       return AnnotationValue.createEnumValue(name, typeName, value.toString());
/* 153:    */     }
/* 154:185 */     return null;
/* 155:    */   }
Example #8
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:    */   }
Example #9
0
/*  47:    */   
/*  48:    */   private static AnnotationValue stringValue(String name, String value)
/*  49:    */   {
/*  50: 86 */     if (StringHelper.isNotEmpty(value)) {
/*  51: 87 */       return AnnotationValue.createStringValue(name, value);
/*  52:    */     }
/*  53: 89 */     return null;
/*  54:    */   }
Example #10
0
/*  91:    */   
/*  92:    */   private static AnnotationValue classValue(String name, String className, ServiceRegistry serviceRegistry)
/*  93:    */   {
/*  94:123 */     if (StringHelper.isNotEmpty(className)) {
/*  95:124 */       return AnnotationValue.createClassValue(name, getType(className, serviceRegistry));
/*  96:    */     }
/*  97:126 */     return null;
/*  98:    */   }
  private void addJoinNodes(QueryNode query, JoinSequence join, FromElement fromElement) {
    JoinFragment joinFragment =
        join.toJoinFragment(
            walker.getEnabledFilters(),
            fromElement.useFromFragment()
                || fromElement.isDereferencedBySuperclassOrSubclassProperty(),
            fromElement.getWithClauseFragment(),
            fromElement.getWithClauseJoinAlias());

    String frag = joinFragment.toFromFragmentString();
    String whereFrag = joinFragment.toWhereFragmentString();

    // If the from element represents a JOIN_FRAGMENT and it is
    // a theta-style join, convert its type from JOIN_FRAGMENT
    // to FROM_FRAGMENT
    if (fromElement.getType() == JOIN_FRAGMENT
        && (join.isThetaStyle() || StringHelper.isNotEmpty(whereFrag))) {
      fromElement.setType(FROM_FRAGMENT);
      fromElement
          .getJoinSequence()
          .setUseThetaStyle(true); // this is used during SqlGenerator processing
    }

    // If there is a FROM fragment and the FROM element is an explicit, then add the from part.
    if (fromElement.useFromFragment() /*&& StringHelper.isNotEmpty( frag )*/) {
      String fromFragment = processFromFragment(frag, join).trim();
      LOG.debugf("Using FROM fragment [%s]", fromFragment);
      processDynamicFilterParameters(fromFragment, fromElement, walker);
    }

    syntheticAndFactory.addWhereFragment(joinFragment, whereFrag, query, fromElement, walker);
  }
 private static AnnotationValue classValue(
     String name, String className, ServiceRegistry serviceRegistry) {
   if (StringHelper.isNotEmpty(className)) {
     return AnnotationValue.createClassValue(name, getType(className, serviceRegistry));
   }
   return null;
 }
 @Override
 public void redefineColumnName(
     String columnName, String propertyName, boolean applyNamingStrategy) {
   if (StringHelper.isNotEmpty(columnName)) {
     if (applyNamingStrategy) {
       getMappingColumn()
           .setName(
               getBuildingContext()
                   .getBuildingOptions()
                   .getPhysicalNamingStrategy()
                   .toPhysicalColumnName(
                       getBuildingContext()
                           .getMetadataCollector()
                           .getDatabase()
                           .toIdentifier(columnName),
                       getBuildingContext()
                           .getMetadataCollector()
                           .getDatabase()
                           .getJdbcEnvironment())
                   .render());
     } else {
       getMappingColumn().setName(columnName);
     }
   }
 }
  @Override
  protected void addColumnBinding(SimpleValue value) {
    if (StringHelper.isEmpty(mappedBy)) {
      // was the column explicitly quoted in the mapping/annotation
      // TODO: in metamodel, we need to better split global quoting and explicit quoting w/ respect
      // to logical names
      boolean isLogicalColumnQuoted = StringHelper.isQuoted(getLogicalColumnName());

      final ObjectNameNormalizer nameNormalizer = getBuildingContext().getObjectNameNormalizer();
      final String logicalColumnName =
          nameNormalizer.normalizeIdentifierQuotingAsString(getLogicalColumnName());
      final String referencedColumn =
          nameNormalizer.normalizeIdentifierQuotingAsString(getReferencedColumn());
      final String unquotedLogColName = StringHelper.unquote(logicalColumnName);
      final String unquotedRefColumn = StringHelper.unquote(referencedColumn);

      String logicalCollectionColumnName =
          StringHelper.isNotEmpty(unquotedLogColName)
              ? unquotedLogColName
              : getPropertyName() + '_' + unquotedRefColumn;
      logicalCollectionColumnName =
          getBuildingContext()
              .getMetadataCollector()
              .getDatabase()
              .getJdbcEnvironment()
              .getIdentifierHelper()
              .toIdentifier(logicalCollectionColumnName, isLogicalColumnQuoted)
              .render();
      getBuildingContext()
          .getMetadataCollector()
          .addColumnNameBinding(value.getTable(), logicalCollectionColumnName, getMappingColumn());
    }
  }
 protected Exporter configureExporter(Exporter exp) {
   QueryExporter exporter = (QueryExporter) exp;
   List queryStrings = new ArrayList();
   if (StringHelper.isNotEmpty(query)) {
     queryStrings.add(query);
   }
   for (Iterator iter = queries.iterator(); iter.hasNext(); ) {
     HQL hql = (HQL) iter.next();
     if (StringHelper.isNotEmpty(hql.query)) {
       queryStrings.add(hql.query);
     }
   }
   exporter.setQueries(queryStrings);
   exporter.setFilename(filename);
   super.configureExporter(exp);
   return exporter;
 }
 static String buildSafeClassName(String className, String defaultPackageName) {
   if (className != null
       && className.indexOf('.') < 0
       && StringHelper.isNotEmpty(defaultPackageName)) {
     className = StringHelper.qualify(defaultPackageName, className);
   }
   return className;
 }
Example #17
0
 public static Identifier resolveIdentifier(
     String explicitName, String defaultName, boolean globalQuoting) {
   String name = StringHelper.isNotEmpty(explicitName) ? explicitName : defaultName;
   if (globalQuoting) {
     name = StringHelper.quote(name);
   }
   return Identifier.toIdentifier(name);
 }
Example #18
0
  @Test
  public void testTableGeneratorIndex() {
    TableSpecification table = SchemaUtil.getTable("ID_GEN", metadata());

    Iterator<org.hibernate.metamodel.spi.relational.Index> indexes = table.getIndexes().iterator();
    assertTrue(indexes.hasNext());
    org.hibernate.metamodel.spi.relational.Index index = indexes.next();
    assertFalse(indexes.hasNext());
    assertTrue("index name is not generated", StringHelper.isNotEmpty(index.getName()));
    assertEquals(1, index.getColumnSpan());
    org.hibernate.metamodel.spi.relational.Column column = index.getColumns().get(0);
    assertEquals("GEN_VALUE", column.getColumnName().getText());
    assertSame(table, index.getTable());
  }
 protected Configuration constructConfiguration() {
   Configuration configuration =
       new Configuration()
           .setProperty(Environment.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName());
   configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
   if (createSchema()) {
     configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
     final String secondSchemaName = createSecondSchema();
     if (StringHelper.isNotEmpty(secondSchemaName)) {
       if (!(getDialect() instanceof H2Dialect)) {
         throw new UnsupportedOperationException(
             "Only H2 dialect supports creation of second schema.");
       }
       Helper.createH2Schema(secondSchemaName, configuration);
     }
   }
   configuration.setProperty(Environment.DIALECT, getDialect().getClass().getName());
   return configuration;
 }
 private void processNamedQueries(EntityElement entityElement) {
   // For backward compatibility, store named queries prefixed with
   // the class name.
   String queryNamePrefix = entityElement.getEntityName();
   queryNamePrefix =
       StringHelper.isNotEmpty(queryNamePrefix)
           ? queryNamePrefix
           : currentMappingDocument
               .getMappingLocalBindingContext()
               .qualifyClassName(entityElement.getName());
   for (final JaxbQueryElement element : entityElement.getQuery()) {
     element.setName(queryNamePrefix + "." + element.getName());
     NamedQueryBindingHelper.bindNamedQuery(element, metadata);
   }
   for (final JaxbSqlQueryElement element : entityElement.getSqlQuery()) {
     element.setName(queryNamePrefix + "." + element.getName());
     NamedQueryBindingHelper.bindNamedSQLQuery(
         element, currentMappingDocument.getMappingLocalBindingContext(), metadata);
   }
 }
  protected void appendCommonColumnInfo(
      StringBuffer annotations, Column column, boolean insertable, boolean updatable) {
    if (column.isUnique()) {
      annotations.append(", unique=").append(column.isUnique());
    }
    if (!column.isNullable()) {
      annotations.append(", nullable=").append(column.isNullable());
    }

    if (!insertable) {
      annotations.append(", insertable=").append(insertable);
    }

    if (!updatable) {
      annotations.append(", updatable=").append(updatable);
    }

    String sqlType = column.getSqlType();
    if (StringHelper.isNotEmpty(sqlType)) {
      annotations.append(", columnDefinition=\"").append(sqlType).append("\"");
    }
  }
  /**
   * Package-protected method to centralize checking of criteria query multi-selects as defined by
   * the {@link CriteriaQuery#multiselect(List)} method.
   *
   * @param selections The selection varargs to check
   * @throws IllegalArgumentException If the selection items are not valid per {@link
   *     CriteriaQuery#multiselect} documentation. <i>&quot;An argument to the multiselect method
   *     must not be a tuple- or array-valued compound selection item.&quot;</i>
   */
  void checkMultiselect(List<Selection<?>> selections) {
    final HashSet<String> aliases =
        new HashSet<String>(CollectionHelper.determineProperSizing(selections.size()));

    for (Selection<?> selection : selections) {
      if (selection.isCompoundSelection()) {
        if (selection.getJavaType().isArray()) {
          throw new IllegalArgumentException(
              "Selection items in a multi-select cannot contain compound array-valued elements");
        }
        if (Tuple.class.isAssignableFrom(selection.getJavaType())) {
          throw new IllegalArgumentException(
              "Selection items in a multi-select cannot contain compound tuple-valued elements");
        }
      }
      if (StringHelper.isNotEmpty(selection.getAlias())) {
        boolean added = aliases.add(selection.getAlias());
        if (!added) {
          throw new IllegalArgumentException(
              "Multi-select expressions defined duplicate alias : " + selection.getAlias());
        }
      }
    }
  }
Example #23
0
 @Override
 public boolean isOrdered() {
   return StringHelper.isNotEmpty(getOrder());
 }
 /**
  * Return the column name if explicit or the concatenation of the property name and the referenced
  * column
  */
 public String logicalCollectionColumnName(
     String columnName, String propertyName, String referencedColumn) {
   return StringHelper.isNotEmpty(columnName)
       ? columnName
       : StringHelper.unqualify(propertyName) + "_" + referencedColumn;
 }
 /** Return the column name or the unqualified property name */
 public String logicalColumnName(String columnName, String propertyName) {
   return StringHelper.isNotEmpty(columnName) ? columnName : StringHelper.unqualify(propertyName);
 }
 private static AnnotationValue stringValue(String name, String value) {
   if (StringHelper.isNotEmpty(value)) {
     return AnnotationValue.createStringValue(name, value);
   }
   return null;
 }
 @Override
 public String getReferencedEntityName() {
   return StringHelper.isNotEmpty(manyToManyElement.getEntityName())
       ? manyToManyElement.getEntityName()
       : bindingContext().qualifyClassName(manyToManyElement.getClazz());
 }
Example #28
0
  /**
   * Method used by JBoss EJB3 (4.2 and above) for parsing Object used by Hibernate OGM as well,
   * consider this some kind of exposed service at the SPI level
   */
  public static List<PersistenceMetadata> deploy(
      URL url,
      Map overrides,
      EntityResolver resolver,
      PersistenceUnitTransactionType defaultTransactionType)
      throws Exception {
    Document doc = loadURL(url, resolver);
    Element top = doc.getDocumentElement();
    // version is mandatory
    final String version = top.getAttribute("version");

    NodeList children = top.getChildNodes();
    ArrayList<PersistenceMetadata> units = new ArrayList<PersistenceMetadata>();
    for (int i = 0; i < children.getLength(); i++) {
      if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) children.item(i);
        String tag = element.getTagName();
        if (tag.equals("persistence-unit")) {
          PersistenceMetadata metadata = parsePersistenceUnit(element);
          metadata.setVersion(version);
          // override properties of metadata if needed
          if (overrides.containsKey(AvailableSettings.PROVIDER)) {
            String provider = (String) overrides.get(AvailableSettings.PROVIDER);
            metadata.setProvider(provider);
          }
          if (overrides.containsKey(AvailableSettings.TRANSACTION_TYPE)) {
            String transactionType = (String) overrides.get(AvailableSettings.TRANSACTION_TYPE);
            metadata.setTransactionType(PersistenceXmlLoader.getTransactionType(transactionType));
          }
          if (overrides.containsKey(AvailableSettings.JTA_DATASOURCE)) {
            String dataSource = (String) overrides.get(AvailableSettings.JTA_DATASOURCE);
            metadata.setJtaDatasource(dataSource);
          }
          if (overrides.containsKey(AvailableSettings.NON_JTA_DATASOURCE)) {
            String dataSource = (String) overrides.get(AvailableSettings.NON_JTA_DATASOURCE);
            metadata.setNonJtaDatasource(dataSource);
          }
          /*
           * if explicit => use it
           * if JTA DS => JTA transaction
           * if non JTA DA => RESOURCE_LOCAL transaction
           * else default JavaSE => RESOURCE_LOCAL
           */
          PersistenceUnitTransactionType transactionType = metadata.getTransactionType();
          Boolean isJTA = null;
          if (StringHelper.isNotEmpty(metadata.getJtaDatasource())) {
            isJTA = Boolean.TRUE;
          } else if (StringHelper.isNotEmpty(metadata.getNonJtaDatasource())) {
            isJTA = Boolean.FALSE;
          }
          if (transactionType == null) {
            if (isJTA == Boolean.TRUE) {
              transactionType = PersistenceUnitTransactionType.JTA;
            } else if (isJTA == Boolean.FALSE) {
              transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
            } else {
              transactionType = defaultTransactionType;
            }
          }
          metadata.setTransactionType(transactionType);
          Properties properties = metadata.getProps();
          ConfigurationHelper.overrideProperties(properties, overrides);
          units.add(metadata);
        }
      }
    }
    return units;
  }
Example #29
0
  private static PersistenceMetadata parsePersistenceUnit(Element top) throws Exception {
    PersistenceMetadata metadata = new PersistenceMetadata();
    String puName = top.getAttribute("name");
    if (StringHelper.isNotEmpty(puName)) {
      LOG.trace("Persistent Unit name from persistence.xml: " + puName);
      metadata.setName(puName);
    }
    NodeList children = top.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
      if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) children.item(i);
        String tag = element.getTagName();
        //				if ( tag.equals( "name" ) ) {
        //					String puName = XmlHelper.getElementContent( element );
        //					log.trace( "FOUND PU NAME: " + puName );
        //					metadata.setName( puName );
        //				}
        //				else
        if (tag.equals("non-jta-data-source")) {
          metadata.setNonJtaDatasource(XmlHelper.getElementContent(element));
        } else if (tag.equals("jta-data-source")) {
          metadata.setJtaDatasource(XmlHelper.getElementContent(element));
        } else if (tag.equals("provider")) {
          metadata.setProvider(XmlHelper.getElementContent(element));
        } else if (tag.equals("class")) {
          metadata.getClasses().add(XmlHelper.getElementContent(element));
        } else if (tag.equals("mapping-file")) {
          metadata.getMappingFiles().add(XmlHelper.getElementContent(element));
        } else if (tag.equals("jar-file")) {
          metadata.getJarFiles().add(XmlHelper.getElementContent(element));
        } else if (tag.equals("exclude-unlisted-classes")) {
          metadata.setExcludeUnlistedClasses(true);
        } else if (tag.equals("delimited-identifiers")) {
          metadata.setUseQuotedIdentifiers(true);
        } else if (tag.equals("validation-mode")) {
          metadata.setValidationMode(XmlHelper.getElementContent(element));
        } else if (tag.equals("shared-cache-mode")) {
          metadata.setSharedCacheMode(XmlHelper.getElementContent(element));
        } else if (tag.equals("properties")) {
          NodeList props = element.getChildNodes();
          for (int j = 0; j < props.getLength(); j++) {
            if (props.item(j).getNodeType() == Node.ELEMENT_NODE) {
              Element propElement = (Element) props.item(j);
              if (!"property".equals(propElement.getTagName())) continue;
              String propName = propElement.getAttribute("name").trim();
              String propValue = propElement.getAttribute("value").trim();
              if (StringHelper.isEmpty(propValue)) {
                // fall back to the natural (Hibernate) way of description
                propValue = XmlHelper.getElementContent(propElement, "");
              }
              metadata.getProps().put(propName, propValue);
            }
          }
        }
      }
    }
    PersistenceUnitTransactionType transactionType =
        getTransactionType(top.getAttribute("transaction-type"));
    if (transactionType != null) metadata.setTransactionType(transactionType);

    return metadata;
  }
  public static void processNamedNativeQuery(
      final HbmLocalMetadataBuildingContext context,
      JaxbHbmNamedNativeQueryType namedQueryBinding,
      String prefix) {
    final String queryName = prefix + namedQueryBinding.getName();
    final NamedSQLQueryDefinitionBuilder builder =
        new NamedSQLQueryDefinitionBuilder()
            .setName(queryName)
            .setComment(namedQueryBinding.getComment())
            .setCacheable(namedQueryBinding.isCacheable())
            .setCacheMode(namedQueryBinding.getCacheMode())
            .setCacheRegion(namedQueryBinding.getCacheRegion())
            .setTimeout(namedQueryBinding.getTimeout())
            .setReadOnly(namedQueryBinding.isReadOnly())
            .setFlushMode(namedQueryBinding.getFlushMode())
            .setFetchSize(namedQueryBinding.getFetchSize())
            .setCallable(namedQueryBinding.isCallable())
            .setResultSetRef(namedQueryBinding.getResultsetRef());

    final ImplicitResultSetMappingDefinition.Builder implicitResultSetMappingBuilder =
        new ImplicitResultSetMappingDefinition.Builder(queryName);

    boolean foundQuery = false;

    for (Object content : namedQueryBinding.getContent()) {
      final boolean wasQuery =
          processNamedQueryContentItem(
              content, builder, implicitResultSetMappingBuilder, namedQueryBinding, context);
      if (wasQuery) {
        foundQuery = true;
      }
    }

    if (!foundQuery) {
      throw new org.hibernate.boot.MappingException(
          String.format(
              "Named native query [%s] did not specify query string", namedQueryBinding.getName()),
          context.getOrigin());
    }

    if (implicitResultSetMappingBuilder.hasAnyReturns()) {
      if (StringHelper.isNotEmpty(namedQueryBinding.getResultsetRef())) {
        throw new org.hibernate.boot.MappingException(
            String.format(
                "Named native query [%s] specified both a resultset-ref and an inline mapping of results",
                namedQueryBinding.getName()),
            context.getOrigin());
      }

      // Building a ResultSet mapping needs access to entity bindings for any entity
      // returns it defines.  But binding for those entities may have not been
      // completed yet.  For "normal" ResultSet mappings, this is already handled by
      // the fact that MetadataSourceProcessor#processResultSetMappings() is called
      // afterQuery all entity hierarchies have been processed.  However, here we are in
      // the middle of processing named-queries (either top-level or entity-level)
      // and have no guarantee that any entity bindings we may need here are bound.
      // So we add the second-pass to bind the implicit resultSet mapping.
      //
      // It is possible to know here whether the second-pass is needed or whether we
      // can immediately bind the ResultSet mapping.
      // todo : consider implementing this (^^) checking

      final ImplicitResultSetMappingDefinition implicitResultSetMappingDefinition =
          implicitResultSetMappingBuilder.build();
      builder.setResultSetRef(implicitResultSetMappingDefinition.getName());
      context
          .getMetadataCollector()
          .addSecondPass(
              new SecondPass() {
                @Override
                public void doSecondPass(Map persistentClasses) throws MappingException {
                  final ResultSetMappingDefinition resultSetMappingDefinition =
                      ResultSetMappingBinder.bind(implicitResultSetMappingDefinition, context);
                  context.getMetadataCollector().addResultSetMapping(resultSetMappingDefinition);
                  NativeSQLQueryReturn[] newQueryReturns =
                      resultSetMappingDefinition.getQueryReturns();
                  final NamedSQLQueryDefinition queryDefinition =
                      context.getMetadataCollector().getNamedNativeQueryDefinition(queryName);
                  if (queryDefinition != null) {
                    queryDefinition.addQueryReturns(newQueryReturns);
                  }
                }
              });
    }

    context.getMetadataCollector().addNamedNativeQuery(builder.createNamedQueryDefinition());
  }