编写示例程序如下,注意这是一个scala程序:
import java.sql.DriverManager
import org.apache.calcite.jdbc.CalciteConnection
import org.apache.calcite.adapter.java.ReflectiveSchema
import java.util.Properties
object CalciteTest {
def main(args: Array[String]) = {
Class.forName("org.apache.calcite.jdbc.Driver");
val info = new Properties();
info.setProperty("lex", "JAVA");
val connection = DriverManager.getConnection("jdbc:calcite:", info);
val calciteConnection =
connection.asInstanceOf[CalciteConnection];
val rootSchema = calciteConnection.getRootSchema();
val hrs = new ReflectiveSchema(new JavaHrSchema())
rootSchema.add("hr", hrs);
val statement = calciteConnection.createStatement();
val resultSet = statement.executeQuery(
"""select * from hr.emps as e
join hr.depts as d on e.deptno = d.deptno""");
while (resultSet.next()) {
(1 to resultSet.getMetaData.getColumnCount).foreach(x => print(resultSet.getObject(x) + "\t"));
println("");
}
resultSet.close();
statement.close();
connection.close();
}
}其中的JavaHrSchema如下,它包含2个字段emps和deps,分别模拟2张表:
public class JavaHrSchema
{
public static class Employee
{
public final int empid;
public final String name;
public final int deptno;
public Employee(int empid, String name, int deptno)
{
this.empid = empid;
this.name = name;
this.deptno = deptno;
}
}
public static class Department
{
public final String name;
public final int deptno;
public Department(int deptno, String name)
{
this.name = name;
this.deptno = deptno;
}
}
public final Employee[] emps = { new Employee(100, "bluejoe", 1),
new Employee(200, "wzs", 2), new Employee(150, "wxz", 1) };
public final Department[] depts = { new Department(1, "dev"),
new Department(2, "market") };
}
运行结果如下:
100 bluejoe 1 dev 1
200 wzs 2 market 2
150 wxz 1 dev 1
这么臃肿的java代码确实有点丑陋,原本想把JavaHrSchema写成如下scala代码:
class HrSchema {
val emps: Array[Employee] = Array(new Employee(100, "bluejoe", 1),
new Employee(200, "wzs", 2),
new Employee(150, "wxz", 1));
val depts: Array[Department] = Array(new Department(1, "dev"),
new Department(2, "market"));
}
class Employee(val empid: Int, val name: String, val deptno: Int) {}
class Department(val deptno: Int, val name: String) {}
结果出错了,原因是ReflectiveSchema读取不到HrSchema里面的public字段,因为scala自动把它变成了private。。。
本文展示了一个使用Scala编写的示例程序,该程序利用Apache Calcite实现了表连接操作。通过对比Java和Scala两种实现方式,揭示了Scala中字段默认为私有的特性,并探讨了解决方案。
1169

被折叠的 条评论
为什么被折叠?



