2015-05-28 70 views
1

我有一個非常類似的問題,在this問題中描述的問題。Querydsl - 左無關表加入

A和B實體之間沒有關係,我想避免添加一個實體。獲得與下面的查詢相同的結果,但使用querydsl的最佳方式是什麼?我將排序和分頁結果,所以子查詢不是最好的方法。

@Entity 
class A { 
    String email; 
} 

@Entity 
class B { 
    String email; 
} 

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

回答

0

您需要在SQL中表達這一點。使用Querydsl SQL或Querydsl JPA原生查詢。

0

正如蒂莫說,使用Querydsl SQL,做像一個動態路徑的東西,如果你想:

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