Querydsl多次加入同一个表

时间:2015-02-04 21:09:01

标签: java querydsl

我们说我有两张表TaskCompanyCompanyidnameTask有两列customerIdproviderId,其链接回id的{​​{1}}列。

使用Querydsl如何两次加入Company表格,以便Companyname指定的每家公司获得customerId

代码可能更好地解释了我尝试的内容:

providerId

哪个生成SQL:

Configuration configuration = new Configuration(templates);
JPASQLQuery query = new JPASQLQuery(this.entityManager, configuration);

QTask task = QTask.task;
QCompany customer = QCompany.company;
QCompany provider = QCompany.company;

JPASQLQuery sql = query.from(task).join(customer).on(customer.id.eq(task.customerId))
    .join(provider).on(provider.id.eq(task.providerId));

return sql.list(task.id, customer.name.as("customerName"), provider.name.as("providerName"));

我真的很喜欢它:

select task.id, company.name as customerName, company.name as providerName from task join company on company.id = task.customerId

我无法弄清楚如何对我加入的表进行别名,因此我可以区分客户和提供商名称。我尝试过做select task.id, customer.name as customerName, provider.name as providerName from task join company as customer on customer.id = task.customerId join company as provider on provider.id = task.providerId 但是没有用。任何人都知道如何做到这一点?

1 个答案:

答案 0 :(得分:22)

如果您需要变量,请执行以下操作

QCompany customer = new QCompany("customer");
QCompany provider = new QCompany("provider");

重新分配默认变量QCompany.company没有帮助