otocon
otocon

Reputation: 1049

Querydsl - left join on unrelated tables

I have a very similar problem to one described in this question.

There is no relation between A and B entities and I want to avoid adding one. What is the best way to get the same results as with query below, but using querydsl? I will be sorting and paging results, so subquery isn't best approach.

@Entity
class A {
   String email;
}

@Entity
class B {
   String email;
}

SELECT * FROM A a left join B b on a.emial=b.email;

Upvotes: 1

Views: 2377

Answers (2)

Nagaraj Tantri
Nagaraj Tantri

Reputation: 5242

As Timo said, use Querydsl SQL and do something like a dynamic path if you want:

PathBuilder<Object> aObj = new PathBuilder<Object>(Object.class, "A");
Path<Object> aAlias = new PathBuilder<Object>(Object.class, "a");

PathBuilder<Object> bObj = new PathBuilder<Object>(Object.class, "B");
Path<Object> bAlias = new PathBuilder<Object>(Object.class, "b");

SQLTemplates templates = MySQLTemplates.builder().printSchema().build();
Configuration configuration = new Configuration(templates);
SQLQueryFactory sQLQueryFactory new SQLQueryFactory(configuration, null);

SQLQuery<?> sqlQuery = sQLQueryFactory.from(aObj.as("a"));
sqlQuery = sqlQuery.innerJoin(bObj, bAlias);

SimpleExpression<T> leftClause = Expressions.stringPath(aAlias, "email");
SimpleExpression<T> rightClause = Expressions.stringPath(bAlias, "email");

sqlQuery = sqlQuery.on(leftClause.eq(rightClause));
sqlQuery = sqlQuery.select(SQLExpressions.all);

// This will give you the required SQL
// select * from A a left join B b on a.emial = b.email;
System.out.println(sqlQuery.getSQL().getSQL());

Upvotes: 2

Timo Westk&#228;mper
Timo Westk&#228;mper

Reputation: 22190

You will need to express this in SQL. Either using Querydsl SQL or Querydsl JPA native queries.

Upvotes: 0

Related Questions