Querydsl joins the same table several times

Let's say I have two tables Task and Company . Company has id and name columns. Task has two customerId and providerId columns that reference the id column for Company .

Using Querydsl, how do I join the Company table twice so that I can get the name for each company specified in customerId and providerId ?

Code that perhaps better explains what I'm trying:

 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")); 

What generates SQL:

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

And I would really like to:

 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 

I could not figure out how to use the alias of the table I joined so that I could distinguish the names of customers and suppliers. I tried making new QCompany("company as provider") , but that didn't work. Does anyone know how to do this?

+5
source share
1 answer

If you need variables, just follow these

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

QCompany.company default variable QCompany.company does not help

+14
source

Source: https://habr.com/ru/post/1212655/


All Articles