最近项目中的一个页面要从Hive中取数据,研究了一下如何把Hive整合进Spring中。
其实还是很简单的,Spring提供了spring-data-hadoop这个包,引进来之后新增一个配置文件就可以了。配置文件样例如下:
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/hadoop" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/hadoop http://www.springframework.org/schema/hadoop/spring-hadoop.xsd"> <beans:bean id="hiveDriver" class="org.apache.hive.jdbc.HiveDriver"/> <beans:bean id="hiveDataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource"> <beans:constructor-arg name="driver" ref="hiveDriver"/> <beans:constructor-arg name="url" value="jdbc:hive2://填数据库地址"/> </beans:bean> <hive-client-factory id="hiveClientFactory" hive-data-source-ref="hiveDataSource"/> <hive-template id="hiveTemplate"/> </beans:beans>
用的时候直接autowire hiveTemplate就可以了。
不过在实际使用的时候遇到了另一个问题,HiveTemplate的功能非常弱鸡,连QueryForObject都没有。于是我用Hive的DataSource配置了一个JdbcTemplate,需要查Object的地方就直接用JdbcTemplate了。
<beans:bean id="hiveJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <beans:property name="dataSource" ref="hiveDataSource"/> </beans:bean>
最后说句题外话,用多了MyBatis之后,再用JdbcTemplate,还真是不习惯。最麻烦的就属QueryForList不能直接返回实体的List了,要么自己写一个映射的方法,要么手动一个个set到实体对象里,无论如何都很麻烦……哎,还是MyBatis好。