简体   繁体   English

如何从jOOQ查询中删除子句(order by)

[英]How a clause (order by) can be removed from a jOOQ query

Is possible to remove a clause (the order by clause in my case) from a dynamically constructed query in jOOQ. 可以从jOOQ中动态构造的查询中删除子句(在我的例子中是order by子句)。

Suppose that after creating the query: 假设创建查询后:

DSLContext create = DSL.using(SQLDialect.POSTGRES);
SelectQuery<Record> query = create.select().from("myTable").where("fk = 1").orderBy(DSL.field("pk")).getQuery();
System.out.println(query.getSQL());
// select * from myTable where (fk = 1) order by pk asc

I want to change the order by clause or remove it to get only 我想更改order by子句或将其删除以仅获取

select * from myTable where (fk = 1)

Is possible make this with jOOQ?. 有可能用jOOQ做这个吗? If is not possible and anyone knows a query builder library that allows this will be also welcome. 如果不可能,并且任何人都知道允许这样做的查询构建器库也将受到欢迎。

This currently cannot be done through the public API. 目前无法通过公共API完成此操作。 In a future jOOQ 4.0, there might be a cleaner separation of the DSL API and the Model API , where such a model API would allow you to freely manipulate all your query parts, including removing objects again from SELECT clauses. 在未来的jOOQ 4.0中, 可能会更清晰地分离DSL API和Model API ,其中这样的模型API允许您自由地操纵所有查询部分,包括再次从SELECT子句中删除对象。

Right now, you have at least two options to implement dynamic SQL: 现在,您至少有两个选项来实现动态SQL:

  1. Don't add the ORDER BY clause until you know whether you need it: 在知道是否需要之前,请不要添加ORDER BY子句:

     SelectQuery<?> select = create .select() .from("myTable") .where("fk = 1") .getQuery(); if (someCondition) select.addOrderBy(DSL.field("pk")); 

    Alternative piece of logic: 替代逻辑:

     List<SortField<?>> orderBy = new ArrayList<>(); if (someCondition) orderBy.add(DSL.field("pk").asc()); create.select() .from("myTable") .where("fk = 1") .orderBy(orderBy); 
  2. Post-process / transform your query using an ExecuteListener or a VisitListener . 使用ExecuteListenerVisitListener对查询进行后处理/转换。 This is more of a workaround in edge-cases, though. 不过,这在边缘情况下更像是一种解决方法。

In your particular case, you should probably go with option 1. Another, more functional approach to tackling dynamic SQL generation is documented here . 在您的特定情况下,您应该使用选项1. 此处记录了另一种更具功能性的方法来处理动态SQL生成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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