/** Overrides the default behaviour to including binding of Grails domain classes. */
  @Override
  protected void secondPassCompile() throws MappingException {
    final Thread currentThread = Thread.currentThread();
    final ClassLoader originalContextLoader = currentThread.getContextClassLoader();
    if (!configLocked) {
      if (LOG.isDebugEnabled())
        LOG.debug(
            "[GrailsAnnotationConfiguration] ["
                + domainClasses.size()
                + "] Grails domain classes to bind to persistence runtime");

      // do Grails class configuration
      configureDomainBinder(binder, grailsApplication, domainClasses);

      for (GrailsDomainClass domainClass : domainClasses) {

        final String fullClassName = domainClass.getFullName();

        String hibernateConfig = fullClassName.replace('.', '/') + ".hbm.xml";
        final ClassLoader loader = originalContextLoader;
        // don't configure Hibernate mapped classes
        if (loader.getResource(hibernateConfig) != null) continue;

        final Mappings mappings = super.createMappings();
        if (!GrailsHibernateUtil.usesDatasource(domainClass, dataSourceName)) {
          continue;
        }

        LOG.debug(
            "[GrailsAnnotationConfiguration] Binding persistent class [" + fullClassName + "]");

        Mapping m = binder.getMapping(domainClass);
        mappings.setAutoImport(m == null || m.getAutoImport());
        binder.bindClass(domainClass, mappings, sessionFactoryBeanName);
      }
    }

    try {
      currentThread.setContextClassLoader(grailsApplication.getClassLoader());
      super.secondPassCompile();
      createSubclassForeignKeys();
    } finally {
      currentThread.setContextClassLoader(originalContextLoader);
    }

    configLocked = true;
  }
Beispiel #2
0
  public static void bindCollectionSecondPass(
      Collection collection,
      java.util.Map persistentClasses,
      Mappings mappings,
      java.util.Map inheritedMetas)
      throws MappingException {

    if (collection.isOneToMany()) {
      OneToMany oneToMany = (OneToMany) collection.getElement();
      PersistentClass persistentClass = mappings.getClass(oneToMany.getReferencedEntityName());

      if (persistentClass == null)
        throw new MappingException(
            "Association "
                + collection.getRole()
                + " references unmapped class: "
                + oneToMany.getReferencedEntityName());

      oneToMany.setAssociatedClass(persistentClass); // Child
    }
  }
Beispiel #3
0
 public static StorageManager getStorage(String vsName) {
   return getStorage(Mappings.getVSensorConfig(vsName));
 }
  @SuppressWarnings({"unchecked"})
  public void doSecondPass(Map persistentClasses) throws MappingException {
    PersistentClass referencedPersistentClass =
        (PersistentClass) persistentClasses.get(referencedEntityName);
    // TODO better error names
    if (referencedPersistentClass == null) {
      throw new AnnotationException("Unknown entity name: " + referencedEntityName);
    }
    if (!(referencedPersistentClass.getIdentifier() instanceof Component)) {
      throw new AssertionFailure(
          "Unexpected identifier type on the referenced entity when mapping a @MapsId: "
              + referencedEntityName);
    }
    Component referencedComponent = (Component) referencedPersistentClass.getIdentifier();
    Iterator<Property> properties = referencedComponent.getPropertyIterator();

    // prepare column name structure
    boolean isExplicitReference = true;
    Map<String, Ejb3JoinColumn> columnByReferencedName =
        new HashMap<String, Ejb3JoinColumn>(joinColumns.length);
    for (Ejb3JoinColumn joinColumn : joinColumns) {
      final String referencedColumnName = joinColumn.getReferencedColumn();
      if (referencedColumnName == null
          || BinderHelper.isEmptyAnnotationValue(referencedColumnName)) {
        break;
      }
      // JPA 2 requires referencedColumnNames to be case insensitive
      columnByReferencedName.put(referencedColumnName.toLowerCase(), joinColumn);
    }
    // try default column orientation
    int index = 0;
    if (columnByReferencedName.isEmpty()) {
      isExplicitReference = false;
      for (Ejb3JoinColumn joinColumn : joinColumns) {
        columnByReferencedName.put("" + index, joinColumn);
        index++;
      }
      index = 0;
    }

    while (properties.hasNext()) {
      Property referencedProperty = properties.next();
      if (referencedProperty.isComposite()) {
        throw new AssertionFailure(
            "Unexpected nested component on the referenced entity when mapping a @MapsId: "
                + referencedEntityName);
      } else {
        Property property = new Property();
        property.setName(referencedProperty.getName());
        property.setNodeName(referencedProperty.getNodeName());
        // FIXME set optional?
        // property.setOptional( property.isOptional() );
        property.setPersistentClass(component.getOwner());
        property.setPropertyAccessorName(referencedProperty.getPropertyAccessorName());
        SimpleValue value = new SimpleValue(mappings, component.getTable());
        property.setValue(value);
        final SimpleValue referencedValue = (SimpleValue) referencedProperty.getValue();
        value.setTypeName(referencedValue.getTypeName());
        value.setTypeParameters(referencedValue.getTypeParameters());
        final Iterator<Column> columns = referencedValue.getColumnIterator();

        if (joinColumns[0].isNameDeferred()) {
          joinColumns[0].copyReferencedStructureAndCreateDefaultJoinColumns(
              referencedPersistentClass, columns, value);
        } else {
          // FIXME take care of Formula
          while (columns.hasNext()) {
            Column column = columns.next();
            final Ejb3JoinColumn joinColumn;
            String logicalColumnName = null;
            if (isExplicitReference) {
              final String columnName = column.getName();
              logicalColumnName =
                  mappings.getLogicalColumnName(columnName, referencedPersistentClass.getTable());
              // JPA 2 requires referencedColumnNames to be case insensitive
              joinColumn = columnByReferencedName.get(logicalColumnName.toLowerCase());
            } else {
              joinColumn = columnByReferencedName.get("" + index);
              index++;
            }
            if (joinColumn == null && !joinColumns[0].isNameDeferred()) {
              throw new AnnotationException(
                  isExplicitReference
                      ? "Unable to find column reference in the @MapsId mapping: "
                          + logicalColumnName
                      : "Implicit column reference in the @MapsId mapping fails, try to use explicit referenceColumnNames: "
                          + referencedEntityName);
            }
            final String columnName =
                joinColumn == null || joinColumn.isNameDeferred()
                    ? "tata_" + column.getName()
                    : joinColumn.getName();
            value.addColumn(new Column(columnName));
            column.setValue(value);
          }
        }
        component.addProperty(property);
      }
    }
  }
 @Override
 protected Map<String, String> getChannelsMapping() {
   return Mappings.getContactChannelsMappingCRMMobileToCRM();
 }
  /**
   * Generates index.html and other top-level frame files.
   *
   * @param Mappings
   * @return 0 if no errors, or 1 if error occurred.
   */
  int generateSrc(Mappings map) {
    try {
      int len;
      Object o[];
      String outputDir = Main.getOutputDir();
      FileWriter fw1, fw2;
      BufferedWriter out1, out2;

      /* Whether rawOffsetIndex list exists or not. */
      LinkedList roi = map.getRawOffsetsIndex();
      if (roi == null) {
        Main.panic("Data not exist. (rawOffsetsIndex)");
        return 1;
      }
      int roi_size = roi.size();
      LinkedList roit = map.getRawOffsetsIndexTable();
      if (roit == null || roit.size() != roi_size) {
        Main.panic("Data not exist. (rawOffsetsIndexTable) Otherwise, Invalid size");
        return 1;
      }

      /* Whether alias list exists or not. */
      TreeMap a = map.getAliases();
      if (a == null) {
        Main.panic("Data not exist. (aliases)");
        return 1;
      }

      timezoneList.putAll(a);

      /* If outputDir doesn't end with file-separator, adds it. */
      if (!outputDir.endsWith(File.separator)) {
        outputDir += File.separatorChar;
      }
      outputDir += docDir + File.separatorChar;

      File outD = new File(outputDir);
      outD.mkdirs();

      /* Creates index.html */
      fw1 = new FileWriter(outputDir + "index.html", false);
      out1 = new BufferedWriter(fw1);

      out1.write(
          header1
              + new Date()
              + header2
              + Main.getVersionName()
              + header4
              + "<FRAMESET cols=\"20%,80%\">\n"
              + "<FRAMESET rows=\"30%,70%\">\n"
              + "<FRAME src=\"overview-frame.html\" name=\"TimeZoneListFrame\">\n"
              + "<FRAME src=\"allTimeZone-frame1.html\" name=\"allTimeZoneFrame\">\n"
              + "</FRAMESET>"
              + "<FRAME src=\"overview-summary.html\" name=\"rightFrame\">\n"
              + "</FRAMESET>\n"
              + "<NOFRAMES>\n"
              + "<H2>\nFrame Alert\n</H2>\n\n"
              + "<P>\n\n"
              + "This document is designed to be viewed using the frames feature. If you see this\n"
              + "message, you are using a non-frame-capable web client.\n"
              + "<BR>\n"
              + "Link to<A HREF=\"overview-summary.html\">Non-frame version.</A>\n"
              + "</NOFRAMES>\n"
              + footer);

      out1.close();
      fw1.close();

      /* Creates overview-frame.html */
      fw1 = new FileWriter(outputDir + "overview-frame.html", false);
      out1 = new BufferedWriter(fw1);

      out1.write(
          header1
              + new Date()
              + header2
              + Main.getVersionName()
              + header4
              + body1
              + "<TABLE BORDER=\"0\" WIDTH=\"100%\">\n<TR>\n"
              + "<TD NOWRAP><FONT size=\"+1\">\n"
              + "<B>Java<sup><font size=-2>TM</font></sup>&nbsp;2&nbsp;Platform<br>Std.&nbsp;Ed.</B></FONT></TD>\n"
              + "</TR>\n</TABLE>\n\n"
              + "<TABLE BORDER=\"0\" WIDTH=\"100%\">\n<TR>\n<TD NOWRAP>"
              + "<P>\n<FONT size=\"+1\">\nAll Time Zones Sorted By:</FONT>\n<BR>\n"
              + "&nbsp;&nbsp;<A HREF=\"allTimeZone-frame1.html\" TARGET=\"allTimeZoneFrame\">GMT offsets</A></FONT>\n<BR>\n"
              + "&nbsp;&nbsp;<A HREF=\"allTimeZone-frame2.html\" TARGET=\"allTimeZoneFrame\">Zone names</A></FONT>\n<BR>"
              + "&nbsp;&nbsp;<A HREF=\"allTimeZone-frame3.html\" TARGET=\"allTimeZoneFrame\">City names</A></FONT>\n"
              + "<P>\n<FONT size=\"+1\">\nContinents and Oceans</FONT>\n<BR>\n");

      o = regionList.keySet().toArray();
      len = regionList.size();
      Object tzo[] = timezoneList.keySet().toArray();
      int tzlen = timezoneList.size();
      for (int i = 0; i < len; i++) {
        Object regionKey = o[i];
        out1.write(
            "&nbsp;&nbsp;<A HREF=\""
                + regionList.get(regionKey)
                + "\" TARGET=\"allTimeZoneFrame\">"
                + regionKey
                + "</A><BR>\n");

        fw2 = new FileWriter(outputDir + regionList.get(regionKey), false);
        out2 = new BufferedWriter(fw2);

        out2.write(
            header1
                + new Date()
                + header3
                + regionKey
                + header4
                + body1
                + "<FONT size=\"+1\"><B>"
                + regionKey
                + "</B></FONT>\n<BR>\n<TABLE>\n<TR>\n<TD>");

        boolean found = false;
        for (int j = 0; j < tzlen; j++) {
          String timezoneKey = (String) tzo[j];
          int regionIndex = timezoneKey.indexOf('/');
          if (regionIndex == -1 || !regionKey.equals(timezoneKey.substring(0, regionIndex))) {
            if (found) {
              break;
            } else {
              continue;
            }
          }

          found = true;
          if (a.containsKey(timezoneKey)) {
            Object realName = a.get(timezoneKey);
            while (a.containsKey(realName)) {
              realName = a.get(realName);
            }
            out2.write(
                timezoneKey
                    + " (alias for "
                    + "<A HREF=\""
                    + timezoneList.get(realName)
                    + "\" TARGET=\"rightFrame\">"
                    + realName
                    + "</A>)");
          } else {
            out2.write(
                "<A HREF=\""
                    + timezoneList.get(timezoneKey)
                    + "\" TARGET=\"rightFrame\">"
                    + timezoneKey
                    + "</A>");
          }
          out2.write("<BR>\n");
        }
        out2.write("</TD>\n</TR>\n</TABLE>\n" + body2 + footer);

        out2.close();
        fw2.close();
      }
      out1.write("</FONT></TD>\n</TR></TABLE>\n" + body2 + footer);

      out1.close();
      fw1.close();

      /* Creates allTimeZone-frame1.html (Sorted by GMT offsets) */
      fw1 = new FileWriter(outputDir + "allTimeZone-frame1.html", false);
      out1 = new BufferedWriter(fw1);

      out1.write(
          header1
              + new Date()
              + header2
              + Main.getVersionName()
              + header4
              + body1
              + "<FONT size=\"+1\"><B>Sorted by GMT offsets</B></FONT>\n"
              + "<BR>\n\n"
              + "<TABLE BORDER=\"0\" WIDTH=\"100%\">\n"
              + "<TR>\n<TD NOWRAP>\n");
      for (int i = 0; i < roi_size; i++) {
        TreeSet perRO = (TreeSet) roit.get(i);
        Iterator keys = perRO.iterator();
        while (keys.hasNext()) {
          Object timezoneKey = keys.next();
          out1.write(
              "<TR>\n<TD><FONT SIZE=\"-1\">("
                  + Time.toGMTFormat(roi.get(i).toString())
                  + ")</FONT></TD>\n<TD>");

          if (a.containsKey(timezoneKey)) {
            Object realName = a.get(timezoneKey);
            while (a.containsKey(realName)) {
              realName = a.get(realName);
            }
            out1.write(
                timezoneKey
                    + " (alias for "
                    + "<A HREF=\""
                    + timezoneList.get(realName)
                    + "\" TARGET=\"rightFrame\">"
                    + realName
                    + "</A>)");
          } else {
            out1.write(
                "<A HREF=\""
                    + timezoneList.get(timezoneKey)
                    + "\" TARGET=\"rightFrame\">"
                    + timezoneKey
                    + "</A>");
          }
          out1.write("</TD>\n</TR>\n");
        }
      }
      out1.write("</FONT></TD>\n</TR>\n</TABLE>\n" + body2 + footer);

      out1.close();
      fw1.close();

      /* Creates allTimeZone-frame2.html (Sorted by zone names) */
      fw1 = new FileWriter(outputDir + "allTimeZone-frame2.html", false);
      out1 = new BufferedWriter(fw1);

      out1.write(
          header1
              + new Date()
              + header2
              + Main.getVersionName()
              + header4
              + body1
              + "<FONT size=\"+1\"><B>Sorted by zone names</B></FONT>\n"
              + "<BR>\n\n"
              + "<TABLE BORDER=\"0\" WIDTH=\"100%\">\n"
              + "<TR>\n<TD NOWRAP>\n");
      o = timezoneList.keySet().toArray();
      len = timezoneList.size();
      for (int i = 0; i < len; i++) {
        Object timezoneKey = o[i];
        if (a.containsKey(timezoneKey)) {
          Object realName = a.get(timezoneKey);
          while (a.containsKey(realName)) {
            realName = a.get(realName);
          }
          out1.write(
              timezoneKey
                  + " (alias for "
                  + "<A HREF=\""
                  + timezoneList.get(realName)
                  + "\" TARGET=\"rightFrame\">"
                  + realName
                  + "</A>)");
        } else {
          out1.write(
              "<A HREF=\""
                  + timezoneList.get(timezoneKey)
                  + "\" TARGET=\"rightFrame\">"
                  + timezoneKey
                  + "</A>");
        }
        out1.write("<BR> \n");
      }
      out1.write("</FONT></TD>\n</TR>\n</TABLE>\n" + body2 + footer);

      out1.close();
      fw1.close();

      /* Creates allTimeZone-frame3.html (Sorted by city names) */
      fw1 = new FileWriter(outputDir + "allTimeZone-frame3.html", false);
      out1 = new BufferedWriter(fw1);

      out1.write(
          header1
              + new Date()
              + header2
              + Main.getVersionName()
              + header4
              + body1
              + "<FONT size=\"+1\"><B>Sorted by city names</B></FONT>\n"
              + "<BR>\n\n"
              + "<TABLE BORDER=\"0\" WIDTH=\"100%\">\n"
              + "<TR>\n<TD NOWRAP>\n");

      Set aliasSet = a.keySet();
      len = aliasSet.size();
      Object aliasNames[] = aliasSet.toArray();
      for (int i = 0; i < len; i++) {
        displayNameList.put(transform((String) aliasNames[i]), aliasNames[i]);
      }

      o = displayNameList.keySet().toArray();
      len = displayNameList.size();
      for (int i = 0; i < len; i++) {
        Object displayName = o[i];
        Object timezoneKey = displayNameList.get(o[i]);
        if (a.containsKey(timezoneKey)) {
          Object realName = a.get(timezoneKey);
          while (a.containsKey(realName)) {
            realName = a.get(realName);
          }
          out1.write(
              displayName
                  + " (alias for "
                  + "<A HREF=\""
                  + timezoneList.get(realName)
                  + "\" TARGET=\"rightFrame\">"
                  + realName
                  + "</A>)");
        } else {
          out1.write(
              "<A HREF=\""
                  + timezoneList.get(timezoneKey)
                  + "\" TARGET=\"rightFrame\">"
                  + displayName
                  + "</A>");
        }
        out1.write("<BR> \n");
      }

      out1.write("</FONT></TD>\n</TR>\n</TABLE>\n" + body2 + footer);

      out1.close();
      fw1.close();

      /* Creates overview-summary.html */
      fw1 = new FileWriter(outputDir + "overview-summary.html", false);
      out1 = new BufferedWriter(fw1);

      out1.write(
          header1
              + new Date()
              + header2
              + Main.getVersionName()
              + header4
              + body1
              + "This is the list of time zones generated from <B>"
              + Main.getVersionName()
              + "</B> for Java 2 Platform, "
              + "Standard Edition. The source code can be obtained "
              + "from ftp site <a href=\"ftp://elsie.nci.nih.gov/pub/\">"
              + "ftp://elsie.nci.nih.gov/pub/</a>. A total of <B>"
              + len
              + "</B> time zones and aliases are supported "
              + "in this edition.\n<BR>\n"
              + "(This site keeps only the latest release.)\nFor the "
              + "format of rules and zones, refer to the zic "
              + "(zoneinfo compiler) man page on "
              + "<a href=\"http://docs.sun.com/ab2/coll.40.6/REFMAN1M/@Ab2PageView/266070?DwebQuery=zic&oqt=zic&Ab2Lang=C&Ab2Enc=iso-8859-1\">Solaris</a> "
              + "or Linux.\n<p>\nNote that this time zone data is not "
              + "a public interface of the Java run-time. No "
              + "applications should rely on the time zone data on "
              + "this web page. Time zone names and time zone data "
              + "may change without any prior notice.\n"
              + body2
              + footer);

      out1.close();
      fw1.close();
    } catch (IOException e) {
      Main.panic("IO error: " + e.getMessage());
      return 1;
    }

    return 0;
  }
Beispiel #7
0
  private String bindCollection(
      PersistentClass rc,
      ForeignKey fromForeignKey,
      ForeignKey toForeignKey,
      Collection collection) {
    ForeignKey targetKey = fromForeignKey;
    String collectionRole = null;
    boolean collectionLazy = false;
    boolean collectionInverse = false;
    TableIdentifier foreignKeyTable = null;
    String tableToClassName;

    if (toForeignKey != null) {
      targetKey = toForeignKey;
    }

    boolean uniqueReference =
        isUniqueReference(targetKey); // TODO: need to look one step further for many-to-many!
    foreignKeyTable = TableIdentifier.create(targetKey.getTable());
    TableIdentifier foreignKeyReferencedTable =
        TableIdentifier.create(targetKey.getReferencedTable());

    if (toForeignKey == null) {

      collectionRole =
          revengStrategy.foreignKeyToCollectionName(
              fromForeignKey.getName(),
              foreignKeyTable,
              fromForeignKey.getColumns(),
              foreignKeyReferencedTable,
              fromForeignKey.getReferencedColumns(),
              uniqueReference);

      tableToClassName = revengStrategy.tableToClassName(foreignKeyTable);
    } else {

      collectionRole =
          revengStrategy.foreignKeyToManyToManyName(
              fromForeignKey,
              TableIdentifier.create(fromForeignKey.getTable()),
              toForeignKey,
              uniqueReference);

      tableToClassName = revengStrategy.tableToClassName(foreignKeyReferencedTable);
    }

    collectionInverse =
        revengStrategy.isForeignKeyCollectionInverse(
            targetKey.getName(),
            foreignKeyTable,
            targetKey.getColumns(),
            foreignKeyReferencedTable,
            targetKey.getReferencedColumns());

    collectionLazy =
        revengStrategy.isForeignKeyCollectionLazy(
            targetKey.getName(),
            foreignKeyTable,
            targetKey.getColumns(),
            foreignKeyReferencedTable,
            targetKey.getReferencedColumns());

    collectionRole = makeUnique(rc, collectionRole);

    String fullRolePath = StringHelper.qualify(rc.getEntityName(), collectionRole);
    if (mappings.getCollection(fullRolePath) != null) {
      log.debug(fullRolePath + " found twice!");
    }

    collection.setRole(fullRolePath); // Master.setOfChildren+
    collection.setInverse(collectionInverse); // TODO: allow overriding this
    collection.setLazy(collectionLazy);
    collection.setFetchMode(FetchMode.SELECT);

    return tableToClassName;
  }
Beispiel #8
0
  /**
   * @param rc
   * @param processed
   * @param table
   * @param object
   */
  private Property bindOneToMany(
      PersistentClass rc, ForeignKey foreignKey, Set processed, Mapping mapping) {

    Table collectionTable = foreignKey.getTable();

    //		Collection collection = new org.hibernate.mapping.Set(rc); // MASTER TODO: allow overriding
    // collection type
    Collection collection =
        new org.hibernate.mapping.List(rc); // MASTER TODO: allow overriding collection type

    collection.setCollectionTable(collectionTable); // CHILD+

    boolean manyToMany = revengStrategy.isManyToManyTable(collectionTable);
    if (manyToMany) {
      // log.debug("Rev.eng said here is a many-to-many");
      // TODO: handle "the other side should influence the name"
    }

    if (manyToMany) {

      ManyToOne element = new ManyToOne(collection.getCollectionTable());
      // TODO: find the other foreignkey and choose the other side.
      Iterator foreignKeyIterator = foreignKey.getTable().getForeignKeyIterator();
      List keys = new ArrayList();
      while (foreignKeyIterator.hasNext()) {
        Object next = foreignKeyIterator.next();
        if (next != foreignKey) {
          keys.add(next);
        }
      }

      if (keys.size() > 1) {
        throw new JDBCBinderException(
            "more than one other foreign key to choose from!"); // todo: handle better ?
      }

      ForeignKey fk = (ForeignKey) keys.get(0);

      String tableToClassName = bindCollection(rc, foreignKey, fk, collection);

      element.setReferencedEntityName(tableToClassName);
      element.addColumn(fk.getColumn(0));
      collection.setElement(element);

    } else {
      String tableToClassName = bindCollection(rc, foreignKey, null, collection);

      OneToMany oneToMany = new OneToMany(collection.getOwner());

      oneToMany.setReferencedEntityName(tableToClassName); // Child
      mappings.addSecondPass(new JDBCCollectionSecondPass(mappings, collection));

      collection.setElement(oneToMany);
    }
    // bind keyvalue
    KeyValue referencedKeyValue;
    String propRef = collection.getReferencedPropertyName();
    if (propRef == null) {
      referencedKeyValue = collection.getOwner().getIdentifier();
    } else {
      referencedKeyValue = (KeyValue) collection.getOwner().getProperty(propRef).getValue();
    }

    SimpleValue keyValue = new DependantValue(collectionTable, referencedKeyValue);
    // keyValue.setForeignKeyName("none"); // Avoid creating the foreignkey
    // key.setCascadeDeleteEnabled( "cascade".equals( subnode.attributeValue("on-delete") ) );
    Iterator columnIterator = foreignKey.getColumnIterator();
    while (columnIterator.hasNext()) {
      Column fkcolumn = (Column) columnIterator.next();
      if (fkcolumn.getSqlTypeCode()
          != null) { // TODO: user defined foreign ref columns does not have a type set.
        guessAndAlignType(
            collectionTable,
            fkcolumn,
            mapping,
            false); // needed to ensure foreign key columns has same type as the "property" column.
      }
      keyValue.addColumn(fkcolumn);
    }

    collection.setKey(keyValue);

    mappings.addCollection(collection);

    return makeCollectionProperty(
        StringHelper.unqualify(collection.getRole()),
        true,
        rc.getTable(),
        foreignKey,
        collection,
        true);
    // return makeProperty(TableIdentifier.create( rc.getTable() ), StringHelper.unqualify(
    // collection.getRole() ), collection, true, true, true, "none", null); // TODO: cascade isn't
    // all by default

  }
Beispiel #9
0
  /**
   * @param manyToOneCandidates
   * @param mappings2
   */
  private void createPersistentClasses(DatabaseCollector collector, Mapping mapping) {
    Map manyToOneCandidates = collector.getOneToManyCandidates();

    for (Iterator iter = mappings.iterateTables(); iter.hasNext(); ) {
      Table table = (Table) iter.next();
      if (table.getColumnSpan() == 0) {
        log.warn("Cannot create persistent class for " + table + " as no columns were found.");
        continue;
      }
      // TODO: this naively just create an entity per table
      // should have an opt-out option to mark some as helper tables, subclasses etc.
      /*if(table.getPrimaryKey()==null || table.getPrimaryKey().getColumnSpan()==0) {
      log.warn("Cannot create persistent class for " + table + " as no primary key was found.");
               continue;
               // TODO: just create one big embedded composite id instead.
           }*/

      if (revengStrategy.isManyToManyTable(table)) {
        log.debug("Ignoring " + table + " as class since rev.eng. says it is a many-to-many");
        continue;
      }

      RootClass rc = new RootClass();
      TableIdentifier tableIdentifier = TableIdentifier.create(table);
      String className = revengStrategy.tableToClassName(tableIdentifier);
      log.debug("Building entity " + className + " based on " + tableIdentifier);
      rc.setEntityName(className);
      rc.setClassName(className);
      rc.setProxyInterfaceName(rc.getEntityName()); // TODO: configurable ?
      rc.setLazy(true);

      rc.setMetaAttributes(safeMeta(revengStrategy.tableToMetaAttributes(tableIdentifier)));

      rc.setDiscriminatorValue(rc.getEntityName());
      rc.setTable(table);
      try {
        mappings.addClass(rc);
      } catch (DuplicateMappingException dme) {
        // TODO: detect this and generate a "permutation" of it ?
        PersistentClass class1 = mappings.getClass(dme.getName());
        Table table2 = class1.getTable();
        throw new JDBCBinderException(
            "Duplicate class name '"
                + rc.getEntityName()
                + "' generated for '"
                + table
                + "'. Same name where generated for '"
                + table2
                + "'");
      }
      mappings.addImport(rc.getEntityName(), rc.getEntityName());

      Set processed = new HashSet();

      PrimaryKeyInfo pki = bindPrimaryKeyToProperties(table, rc, processed, mapping, collector);
      bindColumnsToVersioning(table, rc, processed, mapping);
      bindOutgoingForeignKeys(table, rc, processed);
      bindColumnsToProperties(table, rc, processed, mapping);
      List incomingForeignKeys = (List) manyToOneCandidates.get(rc.getEntityName());
      bindIncomingForeignKeys(rc, processed, incomingForeignKeys, mapping);
      updatePrimaryKey(rc, pki);
    }
  }
  // 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);
  }