以基础的数据类型String、Byte、Short、Integer、Long为例,介绍在Hbase中,如何通过Put操作将类实例对象中的基础数据类型数据写入Hbase。假设Hbase的表字段名称是以类对象所定义字段名的大写。
1,获取类对象字段名,获取一个类对象的所有定义的字段名哈希表,字段名大写-字段名。
private void setClassColumns() {
Field[] fields = TestClass.class.getDeclaredFields();
testClassColumns = Maps.newHashMap();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
//Hbase表字段名是类对象定义字段的大写形式
testClassColumns.put(fields[i].getName().toUpperCase(), fields[i].getName());
}
}
2,根据获取实例化后对象字段值,获取非空值的数据及对应的字段名,分别写入一个List
List
3,将values及columns传入setPut函数,跟进不同数据类型分别向put添加列字段。如果是非Byte属性,都可以直接调用Hbase提供的Bytes静态类进行转换为byte[]数组。Byte字段可以采用直接定义一个字节数组进行赋值。
public Put setPut(String family, String key, String[] columns, List
4,完成数据Put操作后,即可调用Hbase的插入数据操作。
public void insert(String table, Put put) throws Exception {
HTable hTable = null;
Connection connection = getConnection();
try {
hTable = (HTable) connection.getTable(TableName.valueOf(table));
hTable.put(put);
} catch (Exception e) {
logger.error(e.toString());
} finally {
try {
if (hTable != null) {
hTable.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
}
}
}
5,需要注意:a,要判断对象实例对应的数据是否为空,否则有可能出现对象数据和表字段不匹配。b,如果数据类型是Byte时,需要特殊处理,否则入库数据会有问题。



