Ejemplo n.º 1
0
  @SuppressWarnings("unchecked")
  private final Merge<R> toMerge(Configuration configuration) {
    Table<R> i = getInto();

    if (i.getPrimaryKey() != null) {
      Condition condition = null;
      List<Field<?>> key = new ArrayList<Field<?>>();

      for (Field<?> f : i.getPrimaryKey().getFields()) {
        Field<Object> field = (Field<Object>) f;
        Field<Object> value = (Field<Object>) insertMaps.getMap().get(field);

        key.add(value);
        Condition other = field.equal(value);

        if (condition == null) {
          condition = other;
        } else {
          condition = condition.and(other);
        }
      }

      MergeOnConditionStep<R> on = create(configuration).mergeInto(i).usingDual().on(condition);

      // [#1295] Use UPDATE clause only when with ON DUPLICATE KEY UPDATE,
      // not with ON DUPLICATE KEY IGNORE
      MergeNotMatchedStep<R> notMatched = on;
      if (onDuplicateKeyUpdate) {
        notMatched = on.whenMatchedThenUpdate().set(updateMap);
      }

      return notMatched
          .whenNotMatchedThenInsert(insertMaps.getMap().keySet())
          .values(insertMaps.getMap().values());
    } else {
      throw new IllegalStateException(
          "The ON DUPLICATE KEY IGNORE/UPDATE clause cannot be simulated when inserting into non-updatable tables : "
              + getInto());
    }
  }
Ejemplo n.º 2
0
  @SuppressWarnings("unchecked")
  public static <T extends UpdatableRecord<?>> T findById(
      DSLContext context, Class<T> clz, Object id) {
    if (id == null) return null;

    Table<?> table = getTableFromRecordClass(clz);
    if (table == null) return null;

    UniqueKey<?> key = table.getPrimaryKey();
    if (key == null || key.getFieldsArray().length != 1) return null;

    TableField<?, Object> keyField = (TableField<?, Object>) key.getFieldsArray()[0];

    /* Convert object because we are abusing type safety here */
    Object converted = keyField.getDataType().convert(id);

    return (T) context.selectFrom(table).where(keyField.eq(converted)).fetchOne();
  }