1.定义全局变量
private Table table= null;
private final TableName tableName=
TableName. valueOf ( "jxlg:test1" ) ;
private final Logger logger =
Logger. getLogger ( TableDemoDML. class ) ;
2.初始化table对象
@Before
public void init ( ) {
table= HbaseUtil. getTable ( ) ;
}
HbaseUtil工具类
3.插入数据
@Test
public void putData ( ) {
ArrayList< Put> puts= new ArrayList < > ( ) ;
for ( int i= 2 ; i< 40 ; i++ ) {
Put put= new Put ( Bytes. toBytes ( "rk0000" + i) ) ;
put. addColumn ( Bytes. toBytes ( "info1" ) ,
Bytes. toBytes ( "name" ) ,
Bytes. toBytes ( "uzi" + i) ) ;
put. addColumn ( Bytes. toBytes ( "info1" ) ,
Bytes. toBytes ( "age" ) ,
Bytes. toBytes ( "" + new Random ( ) . nextInt ( 21 ) ) ) ;
put. addColumn ( Bytes. toBytes ( "info1" ) ,
Bytes. toBytes ( "sex" ) ,
Bytes. toBytes ( "man" ) ) ;
puts. add ( put) ;
}
try {
table. put ( puts) ;
} catch ( IOException e) {
logger. error ( "获取客户操作失败" ) ;
}
}
4.获取数据
@Test
public void getData ( ) {
Get get= new Get ( Bytes. toBytes ( "rk00001" ) ) ;
try {
Result result = table. get ( get) ;
System. out. println ( "rowkey:" + new String ( result. getRow ( ) ) ) ;
CellScanner cellScanner= result. cellScanner ( ) ;
while ( cellScanner. advance ( ) ) {
Cell cell= cellScanner. current ( ) ;
System. out. print ( "\t"
+ new String ( CellUtil. cloneFamily ( cell) ) ) ;
System. out. print ( ":" +
new String ( CellUtil. cloneQualifier ( cell) ) ) ;
System. out. print ( ": " +
new String ( CellUtil. cloneValue ( cell) ) ) ;
}
} catch ( IOException e) {
logger. error ( "获取客户操作失败" ) ;
}
}
5.多行获取数据
HbaseUtil工具类
@Test
public void MultiGetData ( ) {
ArrayList< Get> array= new ArrayList < > ( ) ;
Get get= new Get ( Bytes. toBytes ( "rk00001" ) ) ;
Get get1= new Get ( Bytes. toBytes ( "rk00002" ) ) ;
Get get2= new Get ( Bytes. toBytes ( "rk00003" ) ) ;
Get get3= new Get ( Bytes. toBytes ( "rk000034" ) ) ;
array. add ( get) ; array. add ( get1) ;
array. add ( get2) ; array. add ( get3) ;
try {
Result [ ] results = table. get ( array) ;
for ( Result result: results) {
HbaseUtil. printRS ( result) ;
}
} catch ( IOException e) {
logger. error ( "获取客户操作失败" ) ;
}
}
6.遍历全部数据
@Test
public void scanData ( ) {
Scan scan =
new Scan ( Bytes. toBytes ( "rk00001" ) , Bytes. toBytes ( "rk00040" ) ) ;
try {
ResultScanner results= table. getScanner ( scan) ;
for ( Result result: results) {
HbaseUtil. printRS ( result) ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
7.删除数据
@Test
public void deleteData ( ) {
Delete del= new Delete ( Bytes. toBytes ( "rk00001" ) ) ;
del. addColumn ( Bytes. toBytes ( "info2" ) , Bytes. toBytes ( "high" ) ) ;
try {
table. delete ( del) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
8.释放资源
@After
public void close ( ) {
HbaseUtil. closeTable ( table) ;
System. out. println ( "执行成功" ) ;
}