Through the use of HBase APIs, the following example shows common operations on HBase, as shown below:
- PackageNet. bkjia. www;
-
- ImportOrg. apache. Hadoop. conf. Configuration;
- ImportOrg. apache. hadoop. hbase. HBaseConfiguration;
- ImportOrg. apache. hadoop. hbase. HColumnDescriptor;
- ImportOrg. apache. hadoop. hbase. HTableDescriptor;
- ImportOrg. apache. hadoop. hbase. KeyValue;
- ImportOrg. apache. hadoop. hbase. client. HBaseAdmin;
- ImportOrg. apache. hadoop. hbase. client. HTable;
- ImportOrg. apache. hadoop. hbase. client. Result;
- ImportOrg. apache. hadoop. hbase. client. resultworkflow;
- ImportOrg. apache. hadoop. hbase. client. Scan;
- ImportOrg. apache. hadoop. hbase. io. BatchUpdate;
-
- Public ClassHBaseDBDao {
-
- // Define the configuration object HBaseConfiguration
- StaticHBaseConfiguration cfg =Null;
- Static{
- Configuration configuration =NewConfiguration ();
- Cfg =NewHBaseConfiguration (configuration );
- }
-
- // Create a table and specify the table name and column family.
- Public Static VoidCreateTable (String tableName, String columnFarily)ThrowsException {
- HBaseAdmin admin =NewHBaseAdmin (cfg );
- If(Admin. tableExists (tableName )){
- System. out. println (tableName +"Does not exist! ");
- System. exit (0);
- }Else{
- HTableDescriptor tableDesc =NewHTableDescriptor (tableName );
- TableDesc. addFamily (NewHColumnDescriptor (columnFarily +":"));
- System. out. println ("Table created successfully! ");
- }
- }
-
- // Add data through HTable. And BatchUpdate add data to an existing table
- Public Static VoidAddData (String tableName, String row, String columnFamily, String column, String data)ThrowsException {
- HTable table =NewHTable (cfg, tableName );
- BatchUpdate update =NewBatchUpdate (row );
- Update. put (columnFamily +":"+ Column, data. getBytes ());
- Table. commit (update );
- System. out. println ("Added successfully! ");
- }
-
- // Display all data. Use the HTable Scan class to obtain information about existing tables.
- Public Static VoidGetAllData (String tableName)ThrowsException {
- HTable table =NewHTable (cfg, tableName );
- Scan scan =NewScan ();
- Resultpartition rs = table. getpartition (scan );
- For(Result r: rs ){
- For(KeyValue kv: r. raw ()){
- System. out. println (NewString (kv. getColumn () +NewString (kv. getValue ()));
- }
- }
- }
-
- // Test the Function
- Public Static VoidMain (String [] args ){
- Try{
- String tableName ="Student";
- HBaseDBDao. createTable (tableName,"C1");
- HBaseDBDao. addData (tableName,"Row1","C1","1","This is row 1 column c1: c1");
- HBaseDBDao. getAllData (tableName );
- }Catch(Exception e ){
- E. printStackTrace ();
- }
- }
- }