Java Client

**Return value**

Future of `QueryResponse` type - a result dataset and additional information like server side metrics. The Response object should be closed after consuming the dataset.

**Examples**

```
// define parameters. They will be sent to the server along with the request.
Map<String, Object> queryParams = new HashMap<>();
queryParams.put("param1", 2);

try (QueryResponse response =
        client.query("SELECT * FROM " + table + " WHERE col1 >= {param1:UInt32}", queryParams, new QuerySettings()).get()) {

    // Create a reader to access the data in a convenient way
    ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response);

    while (reader.hasNext()) {
        reader.next(); // Read the next record from stream and parse it

        // reading data
    }

} catch (Exception e) {
    log.error("Failed to read data", e);
}
```

### queryAll(String sqlQuery)[​](#queryallstring-sqlquery "Direct link to queryAll(String sqlQuery)")

Queries a data in `RowBinaryWithNamesAndTypes` format. Returns the result as a collection. Read performance is the same as with the reader but more memory is required to hold the whole dataset.

**Signatures**

```
List<GenericRecord> queryAll(String sqlQuery)
```

**Parameters**

`sqlQuery` - sql expression to query data from a server.

**Return value**

Complete dataset represented by a list of `GenericRecord` objects that provide access in row style for the result data.

**Examples**

```
try {
    log.info("Reading whole table and process record by record");
    final String sql = "select * from " + TABLE_NAME + " where title <> ''";

    // Read whole result set and process it record by record
    client.queryAll(sql).forEach(row -> {
        double id = row.getDouble("id");
        String title = row.getString("title");
        String url = row.getString("url");

        log.info("id: {}, title: {}, url: {}", id, title, url);
    });
} catch (Exception e) {
    log.error("Failed to read data", e);
}
```

### QuerySettings[​](#querysettings "Direct link to QuerySettings")

Configuration options for query operations.

**Configuration methods**

|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Method Description|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `setQueryId(String queryId)` Sets query ID that will be assigned to the operation.|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `setFormat(ClickHouseFormat format)` Sets response format. See `RowBinaryWithNamesAndTypes` for the full list.| `setMaxExecutionTime(Integer maxExecutionTime)` Sets operation execution time on server. Won't affect read timeout.|  |  |  |  |  |  |  |  |  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `waitEndOfQuery(Boolean waitEndOfQuery)` Requests the server to wait for the end of the query before sending a response.|  |  |  |  |  |  |  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `setUseServerTimeZone(Boolean useServerTimeZone)` Server timezone (see client config) will be used to parse date/time types in the result of an operation. Default `false`.| `setUseTimeZone(String timeZone)` Requests server to use `timeZone` for time conversion. See [session\_timezone](/docs/operations/settings/settings#session_timezone).| `serverSetting(String name, String value)` Sets individual server settings for an operation.|  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | | `serverSetting(String name, Collection values)` Sets individual server settings with multiple values for an operation. Items of the collection should be `String` values.| `setDBRoles(Collection dbRoles)` Sets DB roles to be set before executing an operation. Items of the collection should be `String` values.| `setOption(String option, Object value)` Sets a configuration option in raw format. This isn't a server setting. | | | | | | | | | | | | | | | | | | | | | |

### QueryResponse[​](#queryresponse "Direct link to QueryResponse")

Response object that holds result of query execution. It is only available if the client got a response from a server.

Note

This object should be closed as soon as possible to release a connection because the connection can't be re-used until all data of previous response is fully read.

|  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Method Description|  |  |  |  |  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `ClickHouseFormat getFormat()` Returns a format in which data in the response is encoded.|  |  |  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | --- | --- | | `InputStream getInputStream()` Returns uncompressed byte stream of data in the specified format.|  |  |  |  |  |  | | --- | --- | --- | --- | --- | --- | | `OperationMetrics getMetrics()` Returns object with operation metrics.|  |  |  |  | | --- | --- | --- | --- | | `String getQueryId()` Returns query ID assigned for the operation by the application (through operation settings or by server).|  |  | | --- | --- | | `TimeZone getTimeZone()` Returns timezone that should be used for handling Date/DateTime types in the response. | | | | | | | | | | | |

### Examples[​](#examples "Direct link to Examples")

- Example code is available in [repo](https://github.com/ClickHouse/clickhouse-java/tree/main/examples/client-v2)
- Reference Spring Service [implementation](https://github.com/ClickHouse/clickhouse-java/tree/main/examples/demo-service)

## Common API[​](#common-api "Direct link to Common API")

### getTableSchema(String table)[​](#gettableschemastring-table "Direct link to getTableSchema(String table)")

Fetches table schema for the `table`.

**Signatures**

```
TableSchema getTableSchema(String table)
TableSchema getTableSchema(String table, String database)
```

**Parameters**

`table` - table name for which schema data should be fetched.

`database` - database where the target table is defined.

**Return value**

Returns a `TableSchema` object with list of table columns.

### getTableSchemaFromQuery(String sql)[​](#gettableschemafromquerystring-sql "Direct link to getTableSchemaFromQuery(String sql)")

Fetches schema from a SQL statement.

**Signatures**

```
TableSchema getTableSchemaFromQuery(String sql)
```

**Parameters**

`sql` - "SELECT" SQL statement which schema should be returned.

**Return value**

Returns a `TableSchema` object with columns matching the `sql` expression.

### TableSchema[​](#tableschema "Direct link to TableSchema")

### register(Class<?> clazz, TableSchema schema)[​](#registerclasslt-clazz-tableschema-schema "Direct link to register(Class<?> clazz, TableSchema schema)")

Compiles serialization and deserialization layer for the Java Class to use for writing/reading data with `schema`. The method will create a serializer and deserializer for the pair getter/setter and corresponding column.
Column match is found by extracting its name from a method name. For example, `getFirstName` will be for the column `first_name` or `firstname`.

**Signatures**

```
void register(Class<?> clazz, TableSchema schema)
```

**Parameters**

`clazz` - Class representing the POJO used to read/write data.

`schema` - Data schema to use for matching with POJO properties.

**Examples**

```
client.register(ArticleViewEvent.class, client.getTableSchema(TABLE_NAME));
```

## Usage Examples[​](#usage-examples "Direct link to Usage Examples")

Complete examples code is stored in the repo in a 'example` [folder](https://github.com/ClickHouse/clickhouse-java/tree/main/examples):