Exemplo n.º 1
0
  /**
   * Creates a new entity of the specified type with the optionally specified initial parameters.
   * This method actually inserts a row into the table represented by the entity type and returns
   * the entity instance which corresponds to that row.
   *
   * <p>The {@link DBParam} object parameters are designed to allow the creation of entities which
   * have non-null fields which have no defalut or auto-generated value. Insertion of a row without
   * such field values would of course fail, thus the need for db params. The db params can also be
   * used to set the values for any field in the row, leading to more compact code under certain
   * circumstances.
   *
   * <p>Unless within a transaction, this method will commit to the database immediately and exactly
   * once per call. Thus, care should be taken in the creation of large numbers of entities. There
   * doesn't seem to be a more efficient way to create large numbers of entities, however one should
   * still be aware of the performance implications.
   *
   * <p>This method delegates the action INSERT action to {@link
   * DatabaseProvider#insertReturningKey(EntityManager, Connection, Class, String, boolean, String,
   * DBParam...)}. This is necessary because not all databases support the JDBC <code>
   * RETURN_GENERATED_KEYS</code> constant (e.g. PostgreSQL and HSQLDB). Thus, the database provider
   * itself is responsible for handling INSERTion and retrieval of the correct primary key value.
   *
   * @param type The type of the entity to INSERT.
   * @param params An optional varargs array of initial values for the fields in the row. These
   *     values will be passed to the database within the INSERT statement.
   * @return The new entity instance corresponding to the INSERTed row.
   * @see net.java.ao.DBParam
   * @see net.java.ao.DatabaseProvider#insertReturningKey(EntityManager, Connection, Class, String,
   *     boolean, String, DBParam...)
   */
  public <T extends RawEntity<K>, K> T create(Class<T> type, DBParam... params)
      throws SQLException {
    T back = null;
    String table = null;

    tableNameConverterLock.readLock().lock();
    try {
      table = tableNameConverter.getName(type);
    } finally {
      tableNameConverterLock.readLock().unlock();
    }

    Set<DBParam> listParams = new HashSet<DBParam>();
    listParams.addAll(Arrays.asList(params));

    fieldNameConverterLock.readLock().lock();
    try {
      for (Method method : MethodFinder.getInstance().findAnnotation(Generator.class, type)) {
        Generator genAnno = method.getAnnotation(Generator.class);
        String field = fieldNameConverter.getName(method);
        ValueGenerator<?> generator;

        valGenCacheLock.writeLock().lock();
        try {
          if (valGenCache.containsKey(genAnno.value())) {
            generator = valGenCache.get(genAnno.value());
          } else {
            generator = genAnno.value().newInstance();
            valGenCache.put(genAnno.value(), generator);
          }
        } catch (InstantiationException e) {
          continue;
        } catch (IllegalAccessException e) {
          continue;
        } finally {
          valGenCacheLock.writeLock().unlock();
        }

        listParams.add(new DBParam(field, generator.generateValue(this)));
      }
      // <ian>
      Version version = type.getAnnotation(Version.class);
      if (version != null) {
        // Initialize version upon creation.
        String field = version.value();
        int initial = version.initial();
        listParams.add(new DBParam(field, initial));
      }
      // </ian>
    } finally {
      fieldNameConverterLock.readLock().unlock();
    }

    Connection conn = getProvider().getConnection();
    try {
      Method pkMethod = Common.getPrimaryKeyMethod(type);
      back =
          peer(
              type,
              provider.insertReturningKey(
                  this,
                  conn,
                  Common.getPrimaryKeyClassType(type),
                  Common.getPrimaryKeyField(type, getFieldNameConverter()),
                  pkMethod.getAnnotation(AutoIncrement.class) != null,
                  table,
                  listParams.toArray(new DBParam[listParams.size()])));
    } finally {
      conn.close();
    }

    relationsCache.remove(type);

    back.init();

    return back;
  }