자바에서 하이브 사용하기
1. 하이브 스타트
설치된 하이브를 스타트 시킨다. 터미널에서 hive –service hiveserver 명령어를 치면 자바에서 접근할 수 있게 하이브를 기동시킨다.
참고)
(1) 하이브 설치 : http://blog.naver.com/bb_/220739646411
(2) 하이브 실행 : http://blog.naver.com/bb_/220739653295
2. 라이브러리 가져오기
maven 기준으로 가져와야 하는 라이브러리를 나열하겠다.
(1) Hive Query Language 0.9.0
<!– http://mvnrepository.com/artifact/org.apache.hive/hive-exec –>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
<version>0.9.0</version>
</dependency>
(2) Hive Metastore 0.9.0
<!– http://mvnrepository.com/artifact/org.apache.hive/hive-metastore –>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-metastore</artifactId>
<version>0.9.0</version>
</dependency>
(3) Hive Service 0.9.0
<!– http://mvnrepository.com/artifact/org.apache.hive/hive-service –>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-service</artifactId>
<version>0.9.0</version>
</dependency>
(4) Hive Common 0.9.0
<!– http://mvnrepository.com/artifact/org.apache.hive/hive-common –>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-common</artifactId>
<version>0.9.0</version>
</dependency>
(5) Hive JDBC 0.9.0
<!– http://mvnrepository.com/artifact/org.apache.hive/hive-jdbc –>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>0.9.0</version>
</dependency>
(6) JDO2 API 2.0
<!– http://mvnrepository.com/artifact/javax.jdo/jdo2-api –>
<dependency>
<groupId>javax.jdo</groupId>
<artifactId>jdo2-api</artifactId>
<version>2.0</version>
</dependency>
3. 테이블을 select해서 읽는 자바 소스
package com.com.hive;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class HiveMain {
public static void main(String[] args) {
Connection conn = null;
ResultSet rs = null;
try{
String driver = “org.apache.hadoop.hive.jdbc.HiveDriver”;
Class.forName(driver);
String url = “jdbc:hive://localhost:10000/default”;
//기본 포트가 10000 번이고, 기본데이터베이스 이름이 defualt 임.
String id = “hive”;
String pw = “hive”;
conn = DriverManager.getConnection(url, id, pw);
String sql = “SELECT * FROM dept”;
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
String col1 = rs.getString(1);
String col2 = rs.getString(2);
String col3 = rs.getString(3);
System.out.println( col1 + “/” + col2 + “/” + col3 );
}
rs.close();
conn.close();
}catch(Exception ex){
System.err.println(“main error :”);
ex.printStackTrace();
}finally {
try{
if( rs != null ){
rs.close();
}
}catch(Exception ex){
rs = null;
}
try{
if( conn != null ){
conn.close();
}
}catch(Exception ex){
conn = null;
}
}
}
}