Using the Java API for HBase

Basic Steps to Connect to HBase

First, download the HBase JAR packages, including hbase-core.jar and hbase-client.jar. These packages are located in the HBase binary files and can be downloaded directly from the Apache website.

Download HBase JAR Packages

You can download the HBase JAR packages using the following commands in the command line or IDE:

wget https://dist.apache.org/arrow/0.3.2/hbase-1.4.6.jar
wget https://dist.apache.org/arrow/0.3.2/hbase-client-1.4.6.jar

Load Classes

To use the HBase Java API, you need to load these JAR packages in the class that connects to HBase:

import java.io.File;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.ipc.ClientProtocol;

public class HBaseConnection {
  public static void main(String[] args) throws IOException {
    // Load HBase JAR packages
    Configuration conf = new Configuration();
    conf.set("hbase.zookeeper.property.host", "localhost");
    FileSystem hbaseFs = FileSystem.create(conf);

    // Connect to HBase
    ClientProtocol clientProtocol = (ClientProtocol) hbaseFs.getConf().getSocketFactory().getSocket();
    ZooKeeperConnectionInfo zkInfo = new ZooKeeperConnectionInfo(clientProtocol, conf);

    System.out.println("Successfully connected to HBase");
  }
}

Steps to Operate Tables

Create Table

// Create table
TableFamilyValue tfv = new TableFamilyValue(true);
TableInstance tableInstance = HbaseAdminHelper.getHBaseClient().createTable(new TableName(), tfv);
System.out.println("Successfully created table");

Insert Data

// Insert data
Put put = new Put(TableName.valueOf("mytable").getFamily().getName());
put.add(new QualifierValue("columnfamily", 0, "value".getBytes()));
HbaseAdminHelper.getHBaseClient().insert(tableName, put);
System.out.println("Successfully inserted data");

Reading Data

// Read data
Get get = new Get(TableName.valueOf("mytable").getFamily().getName());
get.add(new QualifierValue("columnfamily", 0));
Result result = HbaseAdminHelper.getHBaseClient().get(get);
System.out.println("Successfully retrieved data");

Delete Table

// Delete table
HbaseAdminHelper.getHBaseClient().dropIfExists(TableName.valueOf("mytable"));
System.out.println("Successfully deleted table");

Summary

Using the HBase Java API requires connecting to HBase, after which you can perform various operations, including creating tables, inserting data, reading data, and deleting tables.

References: