I was wondering if there is any library that can be used to represent SQL queries as objects in Java.
In the code I have plenty of static variables of type java.lang.String that are hand written SQL queries. I would be looking for library having a nice fluent API that allows me to represent the queries as objects rather than strings.
Example:
Query q = select("DATE", "QUOTE")
.from("STOCKMARKET")
.where(eq("CORP", "?"))
.orderBy("DATE", DESC);
SQLJ allows you to code at a higher level than JDBC, by embedding SQL statements directly in your Java code. The SQLJ precompiler that is integrated into JDeveloper translates the SQL into Java plus JDBC code for you. SQLJ with JDeveloper lets you write and debug applications much faster than you can using just JDBC.
Statement objects allow you to execute basic SQL queries and retrieve the results through the ResultSet class, which is described later. To create a Statement instance, you call the createStatement() method on the Connection object you have retrieved using one of the DriverManager.
Querydsl supports querying on SQL, JPA and JDO backends.
The example above becomes :
query.from(stockmarket).where(stockmarket.corp.eq(someVar))
.orderBy(stockmarket.date.desc())
.list(stockmarket.date, stockmarket.quote);
Querydsl uses code generation via APT to mirror an SQL schema to Java query types. This way the queries are fully type-safe (or "schema-compliant" with SQL).
I am the maintainer of Querydsl, so this answer is biased.
I published a comparison of Querydsl to other frameworks here.
These are some good proprietary libraries to create typesafe SQL queries dynamically
Apart from the above, there is always
Your example in jOOQ:
create.select(DATE, QUOTE)
.from(STOCKMARKET)
.where(CORP.equal(123))
.orderBy(DATE.desc());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With