Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any library to represent SQL queries as objects in Java code? [closed]

Tags:

java

sql

api

fluent

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);
like image 472
Tomasz Błachowicz Avatar asked May 05 '09 14:05

Tomasz Błachowicz


People also ask

Can SQL be embedded in Java?

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.

Which object has the SQL method that allows you to execute queries?

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.


2 Answers

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.

like image 142
Timo Westkämper Avatar answered Oct 17 '22 07:10

Timo Westkämper


These are some good proprietary libraries to create typesafe SQL queries dynamically

  • jOOQ: http://www.jooq.org (of which I am the developer)
  • QueryDSL: http://www.querydsl.com
  • JaQu: http://www.h2database.com/html/jaqu.html
  • iciql: http://iciql.com/ (a friendly fork of JaQu)
  • Quaere: http://quaere.codehaus.org
  • Jequel: http://www.jequel.de (in maintenance mode, I think)
  • Squiggle: http://code.google.com/p/squiggle-sql (in maintenance mode, I think)

Apart from the above, there is always

  • Hibernate/JPA CriteriaQuery
  • MyBatis

Your example in jOOQ:

create.select(DATE, QUOTE)
      .from(STOCKMARKET)
      .where(CORP.equal(123))
      .orderBy(DATE.desc());
like image 8
Lukas Eder Avatar answered Oct 17 '22 06:10

Lukas Eder