Java API

更新时间:
复制 MD 格式

HBase provides a native Java API to access and manage data. This topic describes basic examples of how to use the Java API.

Preparations

For more information about the Java API, see the Apache HBase API documentation.
Note To create a connection, you must configure `conf`. The configuration method is different for ApsaraDB for HBase Standard Edition and ApsaraDB for HBase Performance-enhanced Edition. For more information, see the topics linked above.
// Create an HBase connection. This connection is thread-safe and should be created only once during the program's lifecycle. It can be shared by all threads.
// Close the Connection object after the program finishes to prevent connection leaks.
// Use a try-finally block to prevent leaks.
Connection connection = ConnectionFactory.createConnection(conf);

API usage examples

After you establish a connection, you can access the ApsaraDB for HBase Performance-enhanced Edition cluster using the Java API. The following sections provide simple Java examples.

DDL operations

try (Admin admin = connection.getAdmin()){
    // Create a table.
    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("tablename"));
    htd.addFamily(new HColumnDescriptor(Bytes.toBytes("family")));
    // Create a table with only one partition.
    // For production environments, pre-split the table into partitions based on your data.
    admin.createTable(htd);

    // Disable the table.
    admin.disableTable(TableName.valueOf("tablename"));

    // Truncate the table.
    admin.truncateTable(TableName.valueOf("tablename"), true);

    // Delete the table.
    admin.deleteTable(TableName.valueOf("tablename"));
}

DML operations

// The Table object is not thread-safe. Each thread must obtain the corresponding Table object from the connection before performing table operations.
try (Table table = connection.getTable(TableName.valueOf("tablename"))) {
    // Insert data.
    Put put = new Put(Bytes.toBytes("row"));
    put.addColumn(Bytes.toBytes("family"), Bytes.toBytes("qualifier"), Bytes.toBytes("value"));
    table.put(put);

    // Read a single row.
    Get get = new Get(Bytes.toBytes("row"));
    Result res = table.get(get);

    // Delete a row.
    Delete delete = new Delete(Bytes.toBytes("row"));
    table.delete(delete);

    // Scan a range of data.
    Scan scan = new Scan(Bytes.toBytes("startRow"), Bytes.toBytes("endRow"));
    ResultScanner scanner = table.getScanner(scan);
    for (Result result : scanner) {
        // Process the query result.
        // ...
    }
    scanner.close();
}