先说下需求,公司使用oracle的Biee分析数据,Biee本身只支持关系数据库的分析,无法直接读取mongodb的数据。网上搜索到https://blogs.oracle.com/dataintegration/entry/odi_mongodb_and_a_java
里面基本都介绍了,就是利用derby的table functions这个功能。这里有个非常关键的jar,作用是取mongodbd的数据然后组装成java sql的ResultSet,oracle网站里面已经没有了,我找了好久,给出链接:http://www.tuicool.com/articles/NvIFja。
主要开发过程是先到derby里面建一个tableFunctions:
create function employeeTable()
returns table(id int,
name varchar(255),
age int) language java parameter style DERBY_JDBC_RESULT_SET
no sql
external name 'xx.xx.EmployeeTable.read';
然后就是java代码了,读取mongodb的数据:
...
// 使用collection的find方法查找document
DBCursor cursor = collection.find();
ResultSet set = MongodbTableFunction.load(cursor);
...
public class MongodbTableFunction extends EnumeratorTableFunction {
public MongodbTableFunction() throws SQLException {
super(new String[] { "title", "author" });
}
public static ResultSet load(DBCursor cursor) throws SQLException {
MongodbTableFunction mtf = new MongodbTableFunction();
mtf.setEnumeration(cursor);
return mtf;
}
public String[] makeRow(Object obj) throws SQLException {
int col = 0;
String[] row = new String[getColumnCount()];
BSONObject bson = (BSONObject)JSON.parse(obj.toString());
row[col++] = (String) bson.get("title");
row[col++] = (String) bson.get("author");
return row;
}
}
EnumeratorTableFunction 就是某大神的封装的类。然后打成jar包。另外注意的一点是需要把我们写的jar路径放到classpath里面去,如果使用ij,可以直接编辑ij的脚本在它的LOCALCLASSPATH里面加上jar的路径,这样ij里面执行table functions就没有问题了。