简体   繁体   English

如何在Apache MetaModel中加入多个表?

[英]How can I joins multiple tables in Apache MetaModel?

I need to apply joins on multiple tables in Apache MetaModel. 我需要在Apache MetaModel中的多个表上应用连接。 I searched through google but did not find anything related. 我通过谷歌搜索,但没有找到任何相关的。 Can some help me out on this? 有人可以帮我解决这个问题吗?

I guess you tried this approach: 我想你尝试过这种方法:

dataContext.query().from("table1").innerJoin("table2").on("id", "table1_id")...

Indeed it doesn't offer joining more than two tables. 实际上,它不提供加入两个以上的表格。 Doing a join with the condition in the WHERE clause instead of ON should work though: 使用WHERE子句中的条件而不是ON进行连接应该可以正常工作:

    UpdateableDataContext dataContext = new PojoDataContext();

    dataContext.executeUpdate(new UpdateScript() {

        public void run(UpdateCallback callback) {
            Table table1 = callback.createTable(callback.getDataContext().getDefaultSchema(), "table1").withColumn("id")
                    .ofType(ColumnType.INTEGER).asPrimaryKey().execute();

            Table table2 = callback.createTable(callback.getDataContext().getDefaultSchema(), "table2").withColumn("id")
                    .ofType(ColumnType.INTEGER).asPrimaryKey().withColumn("table1_id").ofType(ColumnType.INTEGER)
                    .execute();

            Table table3 = callback.createTable(callback.getDataContext().getDefaultSchema(), "table3").withColumn("id")
                    .ofType(ColumnType.INTEGER).asPrimaryKey().withColumn("table2_id").ofType(ColumnType.INTEGER)
                    .execute();

            callback.insertInto(table1).value("id", 1).execute();
            callback.insertInto(table2).value("id", 1).value("table1_id", 1).execute();
            callback.insertInto(table3).value("id", 1).value("table2_id", 1).execute();
            callback.insertInto(table3).value("id", 2).value("table2_id", 0).execute();
        }
    });

    Table table1 = dataContext.getTableByQualifiedLabel("table1");
    Table table2 = dataContext.getTableByQualifiedLabel("table2");
    Table table3 = dataContext.getTableByQualifiedLabel("table3");

    Column table1id = table1.getColumnByName("id");
    Column table2table1_id = table2.getColumnByName("table1_id");
    Column table3table2_id = table3.getColumnByName("table2_id");

    try (DataSet dataSet = dataContext.query().from(table1).and(table2).and(table3).selectAll().where(table1id).eq(table2table1_id).and(table1id).eq(table3table2_id).execute()) {
        while (dataSet.next()) {
            Row row = dataSet.getRow();
            System.out.println(row);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM