简体   繁体   中英

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;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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