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

编写示例程序如下,注意这是一个scala程序:

import java.sql.DriverManager
import org.apache.calcite.jdbc.CalciteConnection
import org.apache.calcite.adapter.java.ReflectiveSchema
import java.util.Propertiesobject 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。。。



本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部