[英]How to construct query in querydsl without domain classes
在尋找java庫以數據庫無關的方式構建查詢時,我遇到了許多包括iciql,querydsl,jooq,joist,hibernate等。
我想要一些不需要配置文件的東西,可以使用動態模式。 對於我的應用程序,我在運行時了解了數據庫和模式,因此我不會為模式提供任何配置文件或域類。
這似乎是querydsl的核心目標之一,但是通過querydsl的文檔我看到很多用於使用域類構建動態查詢的示例但是我沒有遇到任何解釋如何使用僅僅構建這樣的數據庫不可知查詢我有關於架構的動態信息。
Jooq提供此類功能(請參閱: http : //www.jooq.org/doc/3.2/manual/getting-started/use-cases/jooq-as-a-standalone-sql-builder/ )但如果有限制性許可,我想將我的重點擴展到Oracle或MS SQL(我可能不喜歡但需要支持)。
有querydsl經驗的人能告訴我querydsl是否可以做到這一點,如果是的話,怎么做。
如果有人知道任何其他可以滿足我的要求,那將非常感激。
一個非常簡單的SQL查詢,例如:
@Transactional
public User findById(Long id) {
return new SQLQuery(getConnection(), getConfiguration())
.from(user)
.where(user.id.eq(id))
.singleResult(user);
}
...可以像這樣動態創建(不添加任何糖):
@Transactional
public User findById(Long id) {
Path<Object> userPath = new PathImpl<Object>(Object.class, "user");
NumberPath<Long> idPath = Expressions.numberPath(Long.class, userPath, "id");
StringPath usernamePath = Expressions.stringPath(userPath, "username");
Tuple tuple = new SQLQuery(getConnection(), getConfiguration())
.from(userPath)
.where(idPath.eq(id))
.singleResult(idPath, usernamePath);
return new User(tuple.get(idPath), tuple.get(usernamePath));
}
以下是使用PathBuilder的ponzao解決方案的一小部分變體
@Transactional
public User findById(Long id) {
PathBuilder<Object> userPath = new PathBuilder<Object>(Object.class, "user");
NumberPath<Long> idPath = userPath.getNumber("id", Long.class);
StringPath usernamePath = userPath.getString("username");
Tuple tuple = new SQLQuery(getConnection(), getConfiguration())
.from(userPath)
.where(idPath.eq(id))
.singleResult(idPath, usernamePath);
return new User(tuple.get(idPath), tuple.get(usernamePath));
}
更新:Timo通過向我展示如何執行我想要的操作而無需替換SQLQuery類,從而使我的原始響應無效。 以下是他的評論:
query.getSQL(field1, field2, ... fieldN), getSQL is consistent with the
other methods which also take the projection arguments at last
我刪除了不必要的課程。 下面是一個使用SQLQuery直接獲取SQL字符串而不執行查詢的示例(例如,不使用list
方法):
SQLQuery rquery = new SQLQuery(connection , dialect);
// Use getSQL with projections
rquery.from(qtable)
.where(qtable.qfield1.eq("somevalue"));
SQLBindings bindings = rquery.getSQL(qtable.qfield1, qtable.qfield2);
// Get the SQL string from the SQLBindings
System.out.println(bindings.getSql());
// Get the SQL parameters from the SQLBindings for the parameterized query
System.out.println(bindings.getBindings());
此響應回答了如何使用QueryDSL構建完整的SQL查詢而不實際執行查詢。 它沒有解決您對“動態模式”和“沒有域對象”的額外要求......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.