tags:

views:

677

answers:

6

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);
+1  A: 

Empire-db

http://incubator.apache.org/empire-db/

Quaere

http://xircles.codehaus.org/projects/quaere

Sake
Is quaere active project? There is very little on their website.
pregzt
I'm not quaere user in general. Just remember its as one of java-can-have-linq hype years ago. From the mail-list archive suggest that the project is not very active indeed. FWIW, browsing through the mail list show me some similar projects you may want to take a peek. JaQu (http://www.h2database.com/html/jaqu.html) The bottom of the page also reference so some other related projects
Sake
+4  A: 

http://www.hibernate.org/ Probably most powerfull ORM library for Java. It can do much more then just simple query mapping. So you can easily implement it somwhere else in your application. For your case it can be done somehow like that:

public class LookupCodeName
{
    private String code;
    private String name;

 /*... getter-setters ... */
}

public class someBL {

public List<LookupCodeName> returnSomeEntity() {
      SQLQuery sqlQuery =  (SQLQuery)((HibernateSession)em).getHibernateSession()
                        .createSQLQuery( "SELECT st.name as name, st.code as code FROM someTable st")
                        .addScalar("code")
                        .addScalar("name")
.setResultTransformer(Transformers.aliasToBean(LookupCodeName.class));
    }
return (List<LookupCodeName>)sqlQuery.list();
}
Vanger
Yeah, I know Hibernate, but in your example there is still hardcoded SQL represented as string ("SELECT st.name as name, st.code as code FROM someTable st"). Maybe my question wasn't clear enough, but I wanted to replace string queries with object representation of those rather than employ powerful framework to execute queries.
pregzt
Pregzt, you might want to take a look at Hibernate Criterias
Il-Bhima
I think a criteria API pulls in the wrong direction from having a SQL builder API. On my current project, the original (and long gone) developers used a criteria API, and the current team hates it. We can get a DAO method done using native SQL in half the time it takes to write the criteria API, because the we often end up looking at the SQL the criteria API generates to verify its correctness. If you know the correct SQL already, why count on a SQL generator?
Alan
<quote>If you know the correct SQL already, why count on a SQL generator?</quote>All your comment based at this statement. But why'd you think you "know a correct SQL"? Just some thing, hibernate stands at:1.The sql can be too complex to write it manyally.(Complex entity relations for example)2.If you change entity - you do not need to change criteria for new correct data mapping.3.Do you know on which database your application will be working? Hardcoded SQL kills some independencie.
Vanger
+1  A: 

If you don't want to map string queries, then you must annotate your class as entity and bind it with table then you can use hibernate or java persistance. Example will be too complex though. But, at the end your query will transform to something like this:

find list of entities:

 Criteria c = createCreteria(entityManager, StockMarket.class);
    // you can add "where" clause by using c.add(Restrictions); 
   // like this: c.add(Restrictions.ilike("name", "%somename%"); where "name" is your entity's field
     List<StockMarket> smList = c.list();

find object by id:

 StockMarket sm  = entityManager.find(StockMarket.class, id);
Vanger
+6  A: 

Squiggle

time4tea
James, based on first impresion Squiggle is some sort of the library I was looking for. However the nice, fluent, compact API is missing, but that can be pretty easily added. Cheers!
pregzt
+4  A: 

Jequel looks pretty nifty: http://www.jequel.de/

It uses a fluent interface, so it's easy to read, almost like natural SQL (from the docs):

SqlString sql = select(ARTICLE.OID)
               .from(ARTICLE, ARTICLE_COLOR)
               .where(ARTICLE.OID.eq(ARTICLE_COLOR.ARTICLE_OID)
               .and(ARTICLE.ARTICLE_NO.is_not(NULL)));

It also supports executing queries against a DataSource with parameters, so it handles creation of parameterized queries as well.

mjd79
Looks good. That is something like I was looking for. Cheers!
pregzt
Nice! Don't forget to come back and post your findings. I only found out about it a few days ago, and I haven't had a chance to use it a lot yet, but I plan to in the future.
mjd79
+5  A: 

Querydsl supports querying on SQL, JPA and JDO backends : http://source.mysema.com/display/querydsl/Querydsl

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.

Timo Westkämper
I'll upvote to counter it.
JUST MY correct OPINION