我们说我有两张表Task
和Company
。 Company
列id
和name
。 Task
有两列customerId
和providerId
,其链接回id
的{{1}}列。
使用Querydsl如何两次加入Company
表格,以便Company
和name
指定的每家公司获得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
但是没有用。任何人都知道如何做到这一点?
答案 0 :(得分:22)
如果您需要变量,请执行以下操作
QCompany customer = new QCompany("customer");
QCompany provider = new QCompany("provider");
重新分配默认变量QCompany.company
没有帮助