Example #1
0
  /**
   * @param entity the entity
   * @param metadata the table metadata
   * @since $version
   * @author hceylan
   */
  public EntityTable(EntityTypeImpl<?> entity, TableMetadata metadata) {
    super(entity.getName(), metadata);

    this.entity = entity;

    this.jdbcAdaptor = entity.getMetamodel().getJdbcAdaptor();
  }
Example #2
0
  /**
   * Creates the list of comparables
   *
   * @since $version
   * @author hceylan
   */
  private void createComparables() {
    // order on id
    if (this.mapping.getOrderBy().trim().length() == 0) {
      if (this.mapping.isAssociation()) {
        final EntityTypeImpl<E> type = ((PluralAssociationMapping<?, ?, E>) this.mapping).getType();
        if (type.hasSingleIdAttribute()) {
          this.comparables.add(new ComparableMapping(true, (Mapping<?, ?, ?>) type.getIdMapping()));
        } else {
          for (final Pair<BasicMapping<? super E, ?>, BasicAttribute<?, ?>> pair :
              type.getIdMappings()) {
            this.comparables.add(new ComparableMapping(true, pair.getFirst()));
          }
        }
      } else if (this.mapping.getType().getPersistenceType() == PersistenceType.EMBEDDABLE) {
        throw new MappingException(
            "Embeddable element collections requires OrderBy value",
            this.mapping.getAttribute().getLocator());
      } else {
        this.comparables.add(new ComparableMapping(true, null));
      }
    } else {
      final Iterator<String> i =
          Splitter.on(",").trimResults().split(this.mapping.getOrderBy()).iterator();
      while (i.hasNext()) {
        final Iterator<String> j = Splitter.on(" ").trimResults().split(i.next()).iterator();

        int index = 0;
        String path = null;
        boolean order = true;
        while (j.hasNext()) {
          if (index == 0) {
            path = j.next();
          } else if (index == 1) {
            order = "ASC".equals(j.next().toUpperCase());
          } else {
            throw new MappingException(
                "Invalid order by statement: " + this.mapping.getOrderBy() + ".",
                this.mapping.getAttribute().getLocator());
          }

          index++;
        }

        if (this.mapping.getType().getPersistenceType() == PersistenceType.BASIC) {
          throw new MappingException(
              "Basic element collection must not have OrderBy value",
              this.mapping.getAttribute().getLocator());
        }

        final Mapping<?, ?, ?> mapping = this.mapping.getMapping(path);
        if (mapping == null) {
          throw new MappingException(
              "Sort property cannot be found: " + path, this.mapping.getAttribute().getLocator());
        }

        this.comparables.add(new ComparableMapping(order, mapping));
      }
    }
  }
Example #3
0
  /**
   * Performs the foreign key DDL operations.
   *
   * @param datasource the datasource
   * @param ddlMode the DDL Mode
   * @param entity the entity to perform DDL against
   * @throws BatooException thrown in case of an underlying exception
   * @since $version
   * @author hceylan
   */
  public void performForeignKeysDdl(
      DataSource datasource, DDLMode ddlMode, EntityTypeImpl<?> entity) {
    if ((ddlMode == DDLMode.NONE)) {
      return;
    }

    MetamodelImpl.LOG.info(
        "Performing foreign key DDL operations for entiy {0}, mode {1}", entity.getName(), ddlMode);

    for (final EntityTable table : entity.getTables()) {
      // skip parent tables
      if (table.getEntity() != entity) {
        continue;
      }

      MetamodelImpl.LOG.info(
          "Performing foreign key DDL operations for table {0}, mode {1}",
          table.getQName(), ddlMode);

      for (final ForeignKey foreignKey : table.getForeignKeys()) {
        this.jdbcAdaptor.createForeignKey(datasource, foreignKey);
      }
    }

    for (final AssociationMapping<?, ?, ?> mapping : entity.getAssociations()) {
      final JoinTable table = mapping.getTable();
      // skip not applicable join tables
      if ((table == null) || (table.getEntity() != entity)) {
        continue;
      }

      MetamodelImpl.LOG.info(
          "Performing foreign key DDL operations for join table {0}, mode {1}",
          table.getQName(), ddlMode);

      for (final ForeignKey foreignKey : table.getForeignKeys()) {
        this.jdbcAdaptor.createForeignKey(datasource, foreignKey);
      }
    }

    for (final PluralMapping<?, ?, ?> mapping : entity.getMappingsPlural()) {
      if (!mapping.isAssociation()) {
        final AbstractTable table = (AbstractTable) mapping.getTable();
        MetamodelImpl.LOG.info(
            "Performing foreign key DDL operations for join table {0}, mode {1}",
            table.getQName(), ddlMode);

        for (final ForeignKey foreignKey : table.getForeignKeys()) {
          this.jdbcAdaptor.createForeignKey(datasource, foreignKey);
        }
      }
    }
  }
Example #4
0
  /**
   * Drops all the tables in the database.
   *
   * @param datasource the datasource
   * @since $version
   * @author hceylan
   */
  public void dropAllTables(DataSource datasource) {
    final Set<AbstractTable> tables = Sets.newHashSet();

    for (final EntityTypeImpl<?> entity : this.entities.values()) {

      // collect the entity tables
      for (final EntityTable table : entity.getTables()) {
        // if table belongs to parent then skip
        if (table.getEntity() != entity) {
          continue;
        }

        tables.add(table);
      }

      // collect the join tables
      for (final AssociationMapping<?, ?, ?> mapping : entity.getAssociations()) {
        final JoinTable table = mapping.getTable();

        // skip not applicable tables
        if ((table == null) || (table.getEntity() != entity)) {
          continue;
        }

        tables.add(table);
      }

      // collect the join tables
      for (final PluralMapping<?, ?, ?> mapping : entity.getMappingsPlural()) {
        if (!mapping.isAssociation()) {
          final AbstractTable table = (AbstractTable) mapping.getTable();
          if (table != null) {
            tables.add(table);
          }
        }
      }
    }

    try {
      this.jdbcAdaptor.dropAllForeignKeys(datasource, tables);
      this.jdbcAdaptor.dropAllTables(datasource, tables);
      this.jdbcAdaptor.dropAllSequences(datasource, this.sequenceGenerators.values());
    } catch (final SQLException e) {
      throw new PersistenceException("Cannot drop tables", e);
    }
  }
Example #5
0
  /**
   * Performs the table DDL operations.
   *
   * @param datasource the datasource
   * @param ddlMode the DDL Mode
   * @param entity the entity to perform DDL against
   * @throws BatooException thrown in case of an underlying exception
   * @since $version
   * @author hceylan
   */
  public void performTablesDdl(DataSource datasource, DDLMode ddlMode, EntityTypeImpl<?> entity) {
    MetamodelImpl.LOG.info(
        "Performing DDL operations for entity {0}, mode {1}", entity.getName(), ddlMode);

    // create the entity tables
    for (final EntityTable table : entity.getTables()) {
      // if table belongs to parent then skip
      if (table.getEntity() != entity) {
        continue;
      }

      MetamodelImpl.LOG.info(
          "Performing DDL operations for {0}, mode {1}", table.getQName(), ddlMode);

      this.jdbcAdaptor.createOrUpdateTable(table, datasource, ddlMode);
    }

    // create the join tables
    for (final AssociationMapping<?, ?, ?> mapping : entity.getAssociations()) {
      final JoinTable table = mapping.getTable();

      // skip not applicable tables
      if ((table == null) || (table.getEntity() != entity)) {
        continue;
      }

      this.jdbcAdaptor.createOrUpdateTable(mapping.getTable(), datasource, ddlMode);
    }

    // create the join tables
    for (final PluralMapping<?, ?, ?> mapping : entity.getMappingsPlural()) {
      if (!mapping.isAssociation()) {
        final AbstractTable table = (AbstractTable) mapping.getTable();

        this.jdbcAdaptor.createOrUpdateTable(table, datasource, ddlMode);
      }
    }
  }
Example #6
0
  /**
   * @param entityManagerFactory the entity manager factory
   * @param jdbcAdaptor the JDBC Adaptor
   * @param metadata the metadata
   * @since $version
   * @author hceylan
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public MetamodelImpl(
      EntityManagerFactoryImpl entityManagerFactory,
      JdbcAdaptor jdbcAdaptor,
      MetadataImpl metadata) {
    super();

    this.emf = entityManagerFactory;
    this.jdbcAdaptor = jdbcAdaptor;

    final List<ManagedTypeMetadata> entities = Lists.newArrayList(metadata.getEntityMappings());
    final List<ManagedTypeMetadata> sortedEntities = Lists.newArrayList();

    // sort so that the embeddables are first
    Collections.sort(
        entities,
        new Comparator<ManagedTypeMetadata>() {

          @Override
          public int compare(ManagedTypeMetadata o1, ManagedTypeMetadata o2) {
            if (o1 instanceof EmbeddableMetadata) {
              return -1;
            }

            if (o2 instanceof EmbeddableMetadata) {
              return 1;
            }

            return 0;
          }
        });

    // sort by inheritance
    try {
      while (entities.size() > 0) {
        for (final Iterator<ManagedTypeMetadata> i = entities.iterator(); i.hasNext(); ) {
          final ManagedTypeMetadata entity = i.next();
          final Class<?> c1 = this.emf.getClassloader().loadClass(entity.getClassName());

          boolean independent = true;
          for (final ManagedTypeMetadata entity2 : entities) {
            if (entity == entity2) {
              continue;
            }

            final Class<?> c2 = this.emf.getClassloader().loadClass(entity2.getClassName());

            if (c2.isAssignableFrom(c1)) {
              independent = false;
              break;
            }
          }

          if (independent) {
            i.remove();
            sortedEntities.add(entity);
          }
        }
      }
    } catch (final Exception e) {
    } // not possible at this stage

    for (final ManagedTypeMetadata type : sortedEntities) {
      try {
        final Class<?> clazz = this.emf.getClassloader().loadClass(type.getClassName());

        ManagedTypeImpl<?> parent = null;

        // locate the parent
        Class<?> currentClass = clazz.getSuperclass();
        while ((currentClass != Object.class) && (parent == null)) {
          parent = this.managedType(currentClass);
          currentClass = currentClass.getSuperclass();
        }

        if (type instanceof EntityMetadata) {
          // make sure it extends an identifiable type
          if ((parent != null) && !(parent instanceof IdentifiableTypeImpl)) {
            throw new MappingException(
                "Entities can only extend MappedSuperclasses or other Entities.",
                type.getLocator(),
                parent.getLocator());
          }

          final EntityTypeImpl entity =
              new EntityTypeImpl(this, (IdentifiableTypeImpl) parent, clazz, (EntityMetadata) type);

          this.entities.put(entity.getJavaType(), entity);
          this.entitiesByName.put(entity.getName(), entity);
          this.entitiesByName.put(entity.getJavaType().getName(), entity);
        } else if (type instanceof MappedSuperclassMetadata) {
          // make sure it extends a mapped superclass type
          if ((parent != null) && !(parent instanceof MappedSuperclassTypeImpl)) {
            throw new MappingException(
                "MappedSuperclasses can only extend other MappedSuperclasses.",
                type.getLocator(),
                parent.getLocator());
          }

          final MappedSuperclassTypeImpl mappedSuperclass =
              new MappedSuperclassTypeImpl(
                  this, (MappedSuperclassTypeImpl) parent, clazz, (MappedSuperclassMetadata) type);
          this.mappedSuperclasses.put(mappedSuperclass.getJavaType(), mappedSuperclass);
        }
        if (type instanceof EmbeddableMetadata) {
          // make sure it extends a embeddable type
          if ((parent != null) && !(parent instanceof EmbeddableTypeImpl)) {
            throw new MappingException(
                "Embeddables can only extend a other Embeddables.",
                type.getLocator(),
                parent.getLocator());
          }

          final EmbeddableTypeImpl embeddable =
              new EmbeddableTypeImpl(this, clazz, (EmbeddableMetadata) type);
          this.embeddables.put(embeddable.getJavaType(), embeddable);
        }

      } catch (final ClassNotFoundException e) {
      } // not possible at this time
    }

    this.callbackManager = new CallbackManager(metadata.getEntityListeners());

    this.addNamedQueries(metadata.getNamedQueries());
    for (final ManagedTypeMetadata entity : entities) {
      if (entity instanceof EntityMetadata) {
        this.addNamedQueries(((EntityMetadata) entity).getNamedQueries());
      }
    }
  }