<dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>2.4.6</version> </dependency> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-common</artifactId> <version>2.4.6</version> </dependency> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-annotations</artifactId> <version>2.4.6</version> </dependency> Configuration config = HBaseConfiguration.create(); try (Connection connection = ConnectionFactory.createConnection(config); Admin admin = connection.getAdmin()) { TableName tableName = TableName.valueOf("students"); HTableDescriptor tableDescriptor = new HTableDescriptor(tableName); HColumnDescriptor columnDescriptor = new HColumnDescriptor("info"); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); System.out.println("Table created."); } catch (IOException e) { e.printStackTrace(); } import org.apache.hadoop.hbase.annotations.HBaseColumn; import org.apache.hadoop.hbase.annotations.HBaseTable; @HBaseTable(name = "students") public class Student { @HBaseColumn(family = "info", qualifier = "name") private String name; @HBaseColumn(family = "info", qualifier = "age") private int age; @HBaseColumn(family = "info", qualifier = "score") private double score; // Getters and setters... } Configuration config = HBaseConfiguration.create(); try (Connection connection = ConnectionFactory.createConnection(config)) { Table table = connection.getTable(TableName.valueOf("students")); Student student = new Student(); student.setName("Alice"); student.setAge(20); student.setScore(90.5); Put put = new Put(Bytes.toBytes("row1")); put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes(student.getName())); put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("age"), Bytes.toBytes(student.getAge())); put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("score"), Bytes.toBytes(student.getScore())); table.put(put); Get get = new Get(Bytes.toBytes("row1")); Result result = table.get(get); byte[] nameBytes = result.getValue(Bytes.toBytes("info"), Bytes.toBytes("name")); String name = Bytes.toString(nameBytes); byte[] ageBytes = result.getValue(Bytes.toBytes("info"), Bytes.toBytes("age")); int age = Bytes.toInt(ageBytes); byte[] scoreBytes = result.getValue(Bytes.toBytes("info"), Bytes.toBytes("score")); double score = Bytes.toDouble(scoreBytes); Student retrievedStudent = new Student(); retrievedStudent.setName(name); retrievedStudent.setAge(age); retrievedStudent.setScore(score); System.out.println("Retrieved student: " + retrievedStudent); } catch (IOException e) { e.printStackTrace(); }


上一篇:
下一篇:
切换中文