HBase的java操作,最新API。(查询指定行、列、插入数据等)
关于HBase环境搭建和HBase的原理架构,请见笔者相关博客。
1.HBase对java有着较优秀的支持,本文将介绍如何使用java操作Hbase。
首先是pom依赖:
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-server</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-common</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.操作HBase的关键类:
public class HbaseDemo {
private static Admin admin;
public static void main(String[] args){
try {
createTable("user_table", new String[] { "information", "contact" });
User user = new User("001", "xiaoming", "123456", "man", "20", "13355550021", "1232821@csdn.com");
insertData("user_table", user);
User user2 = new User("002", "xiaohong", "654321", "female", "18", "18757912212", "214214@csdn.com");
insertData("user_table", user2);
List<User> list = getAllData("user_table");
System.out.println("--------------------插入两条数据后--------------------");
for (User user3 : list){
System.out.println(user3.toString());
}
System.out.println("--------------------获取原始数据-----------------------");
getNoDealData("user_table");
System.out.println("--------------------根据rowKey查询--------------------");
User user4 = getDataByRowKey("user_table", "user-001");
System.out.println(user4.toString());
System.out.println("--------------------获取指定单条数据-------------------");
String user_phone = getCellData("user_table", "user-001", "contact", "phone");
System.out.println(user_phone);
User user5 = new User("test-003", "xiaoguang", "789012", "man", "22", "12312132214", "856832@csdn.com");
insertData("user_table", user5);
List<User> list2 = getAllData("user_table");
System.out.println("--------------------插入测试数据后--------------------");
for (User user6 : list2){
System.out.println(user6.toString());
}
deleteByRowKey("user_table", "user-test-003");
List<User> list3 = getAllData("user_table");
System.out.println("--------------------删除测试数据后--------------------");
for (User user7 : list3){
System.out.println(user7.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
//连接集群
public static Connection initHbase() throws IOException {
Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.property.clientPort", "2181");
configuration.set("hbase.zookeeper.quorum", "127.0.0.1");
//集群配置↓
//configuration.set("hbase.zookeeper.quorum", "101.236.39.141,101.236.46.114,101.236.46.113");
configuration.set("hbase.master", "127.0.0.1:60000");
Connection connection = ConnectionFactory.createConnection(configuration);
return connection;
}
//创建表
public static void createTable(String tableNmae, String[] cols) throws IOException {
TableName tableName = TableName.valueOf(tableNmae);
admin = initHbase().getAdmin();
if (admin.tableExists(tableName)) {
System.out.println("表已存在!");
} else {
HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
for (String col : cols) {
HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(col);
hTableDescriptor.addFamily(hColumnDescriptor);
}
admin.createTable(hTableDescriptor);
}
}
//插入数据
public static void insertData(String tableName, User user) throws IOException {
TableName tablename = TableName.valueOf(tableName);
Put put = new Put(("user-" + user.getId()).getBytes());
//参数:1.列族名 2.列名 3.值
put.addColumn("information".getBytes(), "username".getBytes(), user.getUsername().getBytes()) ;
put.addColumn("information".getBytes(), "age".getBytes(), user.getAge().getBytes()) ;
put.addColumn("information".getBytes(), "gender".getBytes(), user.getGender().getBytes()) ;
put.addColumn("contact".getBytes(), "phone".getBytes(), user.getPhone().getBytes());
put.addColumn("contact".getBytes(), "email".getBytes(), user.getEmail().getBytes());
//HTable table = new HTable(initHbase().getConfiguration(),tablename);已弃用
Table table = initHbase().getTable(tablename);
table.put(put);
}
//获取原始数据
public static void getNoDealData(String tableName){
try {
Table table= initHbase().getTable(TableName.valueOf(tableName));
Scan scan = new Scan();
ResultScanner resutScanner = table.getScanner(scan);
for(Result result: resutScanner){
System.out.println("scan: " + result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//根据rowKey进行查询
public static User getDataByRowKey(String tableName, String rowKey) throws IOException {
Table table = initHbase().getTable(TableName.valueOf(tableName));
Get get = new Get(rowKey.getBytes());
User user = new User();
user.setId(rowKey);
//先判断是否有此条数据
if(!get.isCheckExistenceOnly()){
Result result = table.get(get);
for (Cell cell : result.rawCells()){
String colName = Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
if(colName.equals("username")){
user.setUsername(value);
}
if(colName.equals("age")){
user.setAge(value);
}
if (colName.equals("gender")){
user.setGender(value);
}
if (colName.equals("phone")){
user.setPhone(value);
}
if (colName.equals("email")){
user.setEmail(value);
}
}
}
return user;
}
//查询指定单cell内容
public static String getCellData(String tableName, String rowKey, String family, String col){
try {
Table table = initHbase().getTable(TableName.valueOf(tableName));
String result = null;
Get get = new Get(rowKey.getBytes());
if(!get.isCheckExistenceOnly()){
get.addColumn(Bytes.toBytes(family),Bytes.toBytes(col));
Result res = table.get(get);
byte[] resByte = res.getValue(Bytes.toBytes(family), Bytes.toBytes(col));
return result = Bytes.toString(resByte);
}else{
return result = "查询结果不存在";
}
} catch (IOException e) {
e.printStackTrace();
}
return "出现异常";
}
//查询指定表名中所有的数据
public static List<User> getAllData(String tableName){
Table table = null;
List<User> list = new ArrayList<User>();
try {
table = initHbase().getTable(TableName.valueOf(tableName));
ResultScanner results = table.getScanner(new Scan());
User user = null;
for (Result result : results){
String id = new String(result.getRow());
System.out.println("用户名:" + new String(result.getRow()));
user = new User();
for(Cell cell : result.rawCells()){
String row = Bytes.toString(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
//String family = Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength());
String colName = Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
user.setId(row);
if(colName.equals("username")){
user.setUsername(value);
}
if(colName.equals("age")){
user.setAge(value);
}
if (colName.equals("gender")){
user.setGender(value);
}
if (colName.equals("phone")){
user.setPhone(value);
}
if (colName.equals("email")){
user.setEmail(value);
}
}
list.add(user);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
//删除指定cell数据
public static void deleteByRowKey(String tableName, String rowKey) throws IOException {
Table table = initHbase().getTable(TableName.valueOf(tableName));
Delete delete = new Delete(Bytes.toBytes(rowKey));
//删除指定列
//delete.addColumns(Bytes.toBytes("contact"), Bytes.toBytes("email"));
table.delete(delete);
}
//删除表
public static void deleteTable(String tableName){
try {
TableName tablename = TableName.valueOf(tableName);
admin = initHbase().getAdmin();
admin.disableTable(tablename);
admin.deleteTable(tablename);
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.本文以操作User实例为例,新手看下User类:
public class User {
private String id;
private String username;
private String password;
private String gender;
private String age;
private String phone;
private String email;
public User(String id, String username, String password, String gender, String age, String phone, String email) {
this.id = id;
this.username = username;
this.password = password;
this.gender = gender;
this.age = age;
this.phone = phone;
this.email = email;
}
public User(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", age='" + age + '\'' +
", phone='" + phone + '\'' +
", email='" + email + '\'' +
'}';
}
}
4.测试结果如下图:
java操作HBase成功
---------------------
作者:亦心_yan
原文:https://blog.csdn.net/m0_38075425/article/details/81287836
HBase的java操作,最新API。(查询指定行、列、插入数据等)的更多相关文章
- 利用 Java 操作 Jenkins API 实现对 Jenkins 的控制详解
本文转载自利用 Java 操作 Jenkins API 实现对 Jenkins 的控制详解 导语 由于最近工作需要利用 Jenkins 远程 API 操作 Jenkins 来完成一些列操作,就抽空研究 ...
- 072 01 Android 零基础入门 01 Java基础语法 09 综合案例-数组移位 04 综合案例-数组移位-在指定位置处插入数据方法
072 01 Android 零基础入门 01 Java基础语法 09 综合案例-数组移位 04 综合案例-数组移位-在指定位置处插入数据方法 本文知识点:综合案例-数组移位-在指定位置处插入数据方法 ...
- mysql中对表操作----为所有列插入数据
为所有列插入数据 通常情况下,向数据表中插入数据应包含表中所有字段,也就是为表中所有字段添加数据,为表中所有字段添加数据有以下两种方式. 1.INSERT语句中指定所有字段名 使用INSER ...
- 基于py3和pymysql的数据库查询,查询某几列的数据
#python3 #xiaodeng #基于py3和pymysql的数据库查询,查询某几列的数据 import pymysql conn=pymysql.connect(....) cur=conn. ...
- 【hbase】——Java操作Hbase进行建表、删表以及对数据进行增删改查,条件查询
1.搭建环境 新建JAVA项目,添加的包有: 有关Hadoop的hadoop-core-0.20.204.0.jar 有关Hbase的hbase-0.90.4.jar.hbase-0.90.4-tes ...
- java操作elasticsearch实现查询删除和查询所有
后期博客本人都只给出代码,具体的说明在代码中也有注释. 1.查询删除 //查询删除:将查询到的数据进行删除 @Test public void test8() throws UnknownHostEx ...
- HBase(2) Java 操作 HBase 教程
目录 一.简介 二.hbase-client 引入 三.连接操作 四.表操作 五.运行测试 FAQ 参考文档 一.简介 在上一篇文章 HBase 基础入门 中,我们已经介绍了 HBase 的一些基本概 ...
- hbase使用-java操作
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courie ...
- rocketmq(三 java操作rocket API, rocketmq 幂等性)
JAVA操作rocketmq: 1.导入rocketmq所需要的依赖: <dependency> <groupId>com.alibaba.rocketmq</group ...
随机推荐
- springboot-热部署Jrebel
1. 场景描述 介绍下idea+springboot下的热部署插件-Jrebel,贼好用,以前用过好多种,但是总出现不稳定或者会莫名其妙的没有部署新代码. 2.解决方案 springboot自带的de ...
- 《细说PHP》第四版 样章 第23章 自定义PHP接口规范 7
23.5 创建RESTful规范 WebAPI框架 虽然我们现在可以自己实现API了,也了解了RESTful API的设计原则,但让自己实现的API符合RESTful API规范,对很多刚接触API ...
- 3、Hibernate的多表关联
一.数据库中的表关系: 一对一关系 一个人对应一张身份证,一张身份证对应一个人,一对一关系是最好理解的一种关系,在数据库建表的时候可以将人表的主键放置与身份证表里面,也可以将身份证表的主键放置于人表里 ...
- linux远程执行ssh禁用交互方法
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${user}@${ip} ${cmd}
- Java开发桌面程序学习(11)——javafx 鼠标点击,右击,双击
javafx 鼠标事件 给某个控件设置鼠标点击监听器,三个条件分别判断为单击,右击还是双击 单击判断 event.getButton()==MouseButton.PRIMARY 右击判断 event ...
- NetCore 下使用 DataTable 以及可视化工具
DtatTable 在命名空间System.Data下,NetCore2.0及以上支持.但是2017DataTable没有可视化工具,我也没有深研究直接下载的VS2019.然后在网上早了个SQLHel ...
- java基础(23):字节流、字符流
1. 字节流 在前面的学习过程中,我们一直都是在操作文件或者文件夹,并没有给文件中写任何数据.现在我们就要开始给文件中写数据,或者读取文件中的数据. 1.1 字节输出流OutputStream Out ...
- Initialize a Property After Creating an Object创建对象后初始化属性 即如何设置对象的默认值(EF)
In this lesson, you will learn how to set the default value for a particular property of a business ...
- 再来五道剑指offer题目
再来五道剑指offer题目 6.旋转数组的最小数字 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转. 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素. 例如数组{3,4, ...
- Tasteless challenges hard WP
hard Level 5- Fred CMS 十有八九是注入,不过测试引号和转义符并没发现什么,于是跑了下密码字典,竟然发现网页提示 sql injection detected! ,然后发现原来是密 ...