This program connects to HBase, adds a row, reads it, updates it, reads again, deletes it, and checks deletion.
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
public class HBaseCRUDExample {
public static void main(String[] args) throws Exception {
org.apache.hadoop.conf.Configuration config = HBaseConfiguration.create();
try (Connection connection = ConnectionFactory.createConnection(config)) {
TableName tableName = TableName.valueOf("my_table");
try (Table table = connection.getTable(tableName)) {
// Create (Put)
Put put = new Put(Bytes.toBytes("row1"));
put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("name"), Bytes.toBytes("Alice"));
table.put(put);
// Read (Get)
Get get = new Get(Bytes.toBytes("row1"));
Result result = table.get(get);
byte[] value = result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("name"));
System.out.println("Read value: " + Bytes.toString(value));
// Update (Put)
Put putUpdate = new Put(Bytes.toBytes("row1"));
putUpdate.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("name"), Bytes.toBytes("Bob"));
table.put(putUpdate);
// Read updated value
Result updatedResult = table.get(get);
byte[] updatedValue = updatedResult.getValue(Bytes.toBytes("cf"), Bytes.toBytes("name"));
System.out.println("Updated value: " + Bytes.toString(updatedValue));
// Delete
Delete delete = new Delete(Bytes.toBytes("row1"));
table.delete(delete);
// Try to read deleted row
Result deletedResult = table.get(get);
if (deletedResult.isEmpty()) {
System.out.println("Row deleted successfully.");
} else {
System.out.println("Row still exists.");
}
}
}
}
}