使用calcite为对象List封装SQL接口

本文展示了一个使用Scala编写的示例程序,该程序利用Apache Calcite实现了表连接操作。通过对比Java和Scala两种实现方式,揭示了Scala中字段默认为私有的特性,并探讨了解决方案。

编写示例程序如下,注意这是一个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。。。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值