动态创建JOOQ查询 [英] Creating JOOQ query dynamically

查看:1602
本文介绍了动态创建JOOQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据参数集动态创建JOOQ SELECT查询。我不知道如何动态追加它。
请帮助

I need to create a JOOQ SELECT query dynamically based on the set of parameters. I dont know how to append it dynamically. Please help

提前致谢。

推荐答案

jOOQ有两种类型的API来构造查询。

jOOQ has two types of APIs to construct queries.


  • 允许在Java代码中创建内联SQL语句的DSL API,例如

  • The DSL API that allows for creating inline SQL statements in your Java code, e.g.

create.select(T.A, T.B).from(T).where(T.X.eq(3).and(T.Y.eq(5)));


  • 允许增量SQL构建的模型API。您可以随时通过 getQuery() 方法

    您想要做的一个示例在手册中给出:

    An example of what you want to do is given in the manual here:

    https://www.jooq.org/doc/latest/manual/sql-building/sql- statements / dsl-and-non-dsl /

    例如,可选择添加连接:

    For instance, optionally adding a join:

    DSLContext create = DSL.using(configuration);
    SelectQuery query = create.selectQuery();
    query.addFrom(AUTHOR);
    
    // Join books only under certain circumstances
    if (join)
        query.addJoin(BOOK, BOOK.AUTHOR_ID.equal(AUTHOR.ID));
    
    Result<?> result = query.fetch();
    

    或者,可选择添加条件/谓词:

    Or, optinally adding conditions / predicates:

    query.addConditions(BOOK.TITLE.like("%Java%"));
    query.addConditions(BOOK.LANGUAGE_CD.eq("en"));
    

    更新:鉴于您的意见,这就是您所寻找的:

    UPDATE: Given your comments, that's what you're looking for:

    // Retrieve search strings from your user input (just an example)
    String titleSearchString = userInput.get("TITLE");
    String languageSearchString = userInput.get("LANGUAGE");
    boolean lookingForTitles = titleSearchString != null;
    boolean lookingForLanguages = languageSearchString != null;
    
    // Add only those conditions that the user actually provided:
    if (lookingForTitles)
        query.addConditions(BOOK.TITLE.like("%" + titleSearchString + "%"));
    else if (lookingForLanguages)
        query.addConditions(BOOK.LANGUAGE_CD.eq(languageSearchString));
    

    注意,您也可以使用 Field.compare(Comparator,Object) 方法:

    Note, you can also use the Field.compare(Comparator, Object) methods:

    // Initialise your dynamic arguments
    Field<String> field = BOOK.TITLE;
    Comparator comparator = Comparator.LIKE;
    String value = "%" + titleSearchString + "%";
    
    // Pass them to the field.compare() method
    query.addConditions(field.compare(comparator, value));
    

    有关详细信息,请考虑 org.jooq.SelectQuery Javadoc

    For more info, consider the org.jooq.SelectQuery Javadoc

    这篇关于动态创建JOOQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆