private SearchRequestBuilder prepareSearch(Query query) {
    Assert.notNull(query.getIndices(), "No index defined for Query");
    Assert.notNull(query.getTypes(), "No type defined for Query");

    int startRecord = 0;
    SearchRequestBuilder searchRequestBuilder =
        client
            .prepareSearch(toArray(query.getIndices()))
            .setSearchType(query.getSearchType())
            .setTypes(toArray(query.getTypes()));

    if (query.getPageable() != null) {
      startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
      searchRequestBuilder.setSize(query.getPageable().getPageSize());
    }
    searchRequestBuilder.setFrom(startRecord);

    if (!query.getFields().isEmpty()) {
      searchRequestBuilder.addFields(toArray(query.getFields()));
    }

    if (query.getSort() != null) {
      for (Sort.Order order : query.getSort()) {
        searchRequestBuilder.addSort(
            order.getProperty(),
            order.getDirection() == Sort.Direction.DESC ? SortOrder.DESC : SortOrder.ASC);
      }
    }

    if (query.getMinScore() > 0) {
      searchRequestBuilder.setMinScore(query.getMinScore());
    }
    return searchRequestBuilder;
  }
  private <T> MultiGetResponse getMultiResponse(Query searchQuery, Class<T> clazz) {

    String indexName =
        isNotEmpty(searchQuery.getIndices())
            ? searchQuery.getIndices().get(0)
            : getPersistentEntityFor(clazz).getIndexName();
    String type =
        isNotEmpty(searchQuery.getTypes())
            ? searchQuery.getTypes().get(0)
            : getPersistentEntityFor(clazz).getIndexType();

    Assert.notNull(indexName, "No index defined for Query");
    Assert.notNull(type, "No type define for Query");
    Assert.notEmpty(searchQuery.getIds(), "No Id define for Query");

    MultiGetRequestBuilder builder = client.prepareMultiGet();

    for (String id : searchQuery.getIds()) {

      MultiGetRequest.Item item = new MultiGetRequest.Item(indexName, type, id);

      if (searchQuery.getRoute() != null) {
        item = item.routing(searchQuery.getRoute());
      }

      if (searchQuery.getFields() != null && !searchQuery.getFields().isEmpty()) {
        item = item.fields(toArray(searchQuery.getFields()));
      }
      builder.add(item);
    }
    return builder.execute().actionGet();
  }
Exemplo n.º 3
0
  /**
   * Selects all entities matching the given type and {@link Query}. By default, the entities will
   * be created based on the values within the primary key field for the specified type (this is
   * usually the desired behavior).
   *
   * <p>Example:
   *
   * <pre>
   * manager.find(Person.class, Query.select().where("name LIKE ? OR age &gt; ?", "Joe", 9).limit(10));
   * </pre>
   *
   * <p>This method delegates the call to {@link #find(Class, String, Query)}, passing the primary
   * key field for the given type as the <code>String</code> parameter.
   *
   * @param type The type of the entities to retrieve.
   * @param query The {@link Query} instance to be used to determine the results.
   * @return An array of entities of the given type which match the specified query.
   */
  public <T extends RawEntity<K>, K> T[] find(Class<T> type, Query query) throws SQLException {
    String selectField = Common.getPrimaryKeyField(type, getFieldNameConverter());
    query.resolveFields(type, getFieldNameConverter());

    String[] fields = query.getFields();
    if (fields.length == 1) {
      selectField = fields[0];
    }

    return find(type, selectField, query);
  }
Exemplo n.º 4
0
 private void assertValues() {
   if (!valuesToInsert.isEmpty()) {
     if (columns.isEmpty()) {
       throw new IllegalStateException("No columns were specified to insert into.");
     }
     assertValueSetSizes(columns.size());
   } else if (query != null) {
     if (columns.size() != query.getFields().size()) {
       throw new IllegalStateException(
           "Number of properties being selected must match the number of columns " + "specified.");
     }
   } else if (!defaultValues) {
     throw new IllegalStateException("No values to insert were specified.");
   }
 }
Exemplo n.º 5
0
  /**
   * Selects all entities of the specified type which match the given <code>Query</code>. This
   * method creates a <code>PreparedStatement</code> using the <code>Query</code> instance specified
   * against the table represented by the given type. This query is then executed (with the
   * parameters specified in the query). The method then iterates through the result set and
   * extracts the specified field, mapping an entity of the given type to each row. This array of
   * entities is returned.
   *
   * @param type The type of the entities to retrieve.
   * @param field The field value to use in the creation of the entities. This is usually the
   *     primary key field of the corresponding table.
   * @param query The {@link Query} instance to use in determining the results.
   * @return An array of entities of the given type which match the specified query.
   */
  public <T extends RawEntity<K>, K> T[] find(Class<T> type, String field, Query query)
      throws SQLException {
    List<T> back = new ArrayList<T>();

    query.resolveFields(type, getFieldNameConverter());

    // <ian>
    Version version = type.getAnnotation(Version.class);
    if (version != null && !version.findInitial()) {
      // Add initial version check to exclude
      // objects that have only been created and not saved yet.
      if (query.getWhereClause() == null) {
        query.where(version.value() + " != ?", version.initial());
      } else {
        // Preserve existing WHERE clause and parameters
        String whereClause =
            new StringBuilder()
                .append(query.getWhereClause())
                .append(" AND ")
                .append(version.value())
                .append(" != ?")
                .toString();
        Object[] paramsOld = query.getWhereParams();
        Object[] paramsNew = new Object[paramsOld.length + 1];
        System.arraycopy(paramsOld, 0, paramsNew, 0, paramsOld.length);
        paramsNew[paramsNew.length - 1] = version.initial();
        query.setWhereClause(whereClause);
        query.setWhereParams(paramsNew);
      }
    }
    // </ian>

    Preload preloadAnnotation = type.getAnnotation(Preload.class);
    if (preloadAnnotation != null) {
      if (!query.getFields()[0].equals("*") && query.getJoins().isEmpty()) {
        String[] oldFields = query.getFields();
        List<String> newFields = new ArrayList<String>();

        for (String newField : preloadAnnotation.value()) {
          newField = newField.trim();

          int fieldLoc = -1;
          for (int i = 0; i < oldFields.length; i++) {
            if (oldFields[i].equals(newField)) {
              fieldLoc = i;
              break;
            }
          }

          if (fieldLoc < 0) {
            newFields.add(newField);
          } else {
            newFields.add(oldFields[fieldLoc]);
          }
        }

        if (!newFields.contains("*")) {
          for (String oldField : oldFields) {
            if (!newFields.contains(oldField)) {
              newFields.add(oldField);
            }
          }
        }

        query.setFields(newFields.toArray(new String[newFields.size()]));
      }
    }

    Connection conn = getProvider().getConnection();
    try {
      String sql = null;
      tableNameConverterLock.readLock().lock();
      try {
        sql = query.toSQL(type, provider, tableNameConverter, getFieldNameConverter(), false);
      } finally {
        tableNameConverterLock.readLock().unlock();
      }

      Logger.getLogger("net.java.ao").log(Level.INFO, sql);
      PreparedStatement stmt =
          conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      provider.setQueryStatementProperties(stmt, query);

      query.setParameters(this, stmt);

      ResultSet res = stmt.executeQuery();
      provider.setQueryResultSetProperties(res, query);

      while (res.next()) {
        T entity =
            peer(
                type,
                Common.getPrimaryKeyType(type)
                    .pullFromDatabase(this, res, Common.getPrimaryKeyClassType(type), field));
        CacheLayer cacheLayer = getProxyForEntity(entity).getCacheLayer(entity);

        for (String cacheField : query.getCanonicalFields(type, fieldNameConverter)) {
          cacheLayer.put(cacheField, res.getObject(cacheField));
        }

        back.add(entity);
      }
      res.close();
      stmt.close();
    } finally {
      conn.close();
    }

    return back.toArray((T[]) Array.newInstance(type, back.size()));
  }