如何在没有域类的情况下在 querydsl 中构造查询

Mic*_*ckJ 5 java sql database-agnostic querydsl jooq

在寻找 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 是否可以实现这样的事情,如果可以,如何实现。

如果有人知道任何其他可以满足我的要求的人,我将不胜感激。

pon*_*zao 6

一个非常简单的 SQL 查询,例如:

@Transactional
public User findById(Long id) {
    return new SQLQuery(getConnection(), getConfiguration())
      .from(user)
      .where(user.id.eq(id))
      .singleResult(user);
}
Run Code Online (Sandbox Code Playgroud)

...可以像这样动态创建(不添加任何糖):

@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));
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*per 5

这是 ponzao 使用 PathBuilder 的解决方案的一个小变化

@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));
}
Run Code Online (Sandbox Code Playgroud)