How to dynamically generate SQL query based on user’s selections?

后端 未结 5 1363
误落风尘
误落风尘 2021-01-22 18:56

This is the same question as:

How to dynamically generate SQL query based on user's selections?

The only difference is, that I\'m interested in seeing soluti

相关标签:
5条回答
  • 2021-01-22 19:16

    I use the Querydsl framework because I'm using JPA 1.0 which does not include the Criteria API and I also needed the features you described. Writing Querydsl code is easy and the code is shorter than Criteria API code. Querydsl is free to use and it supports typesafe queries.

    0 讨论(0)
  • 2021-01-22 19:18

    There are many different tools the best i think are querydsl, torpedoquery e Object Query, this three allow to write typesafe query, otherwise you can use criteria api, and if you are using jpa 2 also JPA2 Typesafe Query.

    with all this tools you can build a query at runtime!!

    0 讨论(0)
  • 2021-01-22 19:23

    If you want to do this in JPA 1.X, you can use custom query builder as described here http://rrusin.blogspot.com/2010/02/jpa-query-builder.html. This enables creating queries like this:

    return new JpaQueryBuilder().buildQuery(em,
                    new Object[] {
                        "select c from Car c where c.name is not null",
                        new JQBParam("name", name, " and c.name = :name"),
                        new JQBParam("type", type, " and c.type = :type")
                    }
                )
    
    0 讨论(0)
  • 2021-01-22 19:31

    In Hibernate, you can use Criteria queries.

    In Toplink, we got Expression, and ExpressionBuilder.

    0 讨论(0)
  • 2021-01-22 19:34

    In my code, I'm using AND and OR objects for this. They take lists as parameters (looks nice with Java 5's variadic arguments) and concatenate them in Strings with the necessary spaces and parentheses. Pseudo code:

    AND(WhereCond ... conds) { this.conds = conds; }
    toString() { return conds.length == 0 ? "" : "(" + join(conds, " AND ") + ")" };
    

    where join() converts the object array to string array and then joins the elements with the parameter.

    0 讨论(0)
提交回复
热议问题