Thursday, June 25, 2009

Weekly Source Code: LINQ for Java Part 2

I hope everybody had a nice week, even if the winter is upon us - freezing cold with rain etc. Time to get the blankets / heaters out.

Last week I introduced JoSQL, this week I continue to show a sample JoSQL query... we start off with a keep it simple (KISS) sample with some points to remember.

Sample Query:

The goal of this JoSQL query is to get a list of contracts that all have a given product:

List contracts = .... // here we get a list of contracts

Query q = new Query();
q.parse("select * from com.sales.Contract where productId = :p");
q.setVariable("p", 5);
QueryResults qr = q.execute(contracts);
List contractResult = qr.getResults ();
  1. All JoSQL classes are kept in the org.josql package, Eclipse IDE will import these nicely for you.
  2. We start by creating a Query object instance this is where our query starts.
  3. q.parse will check your query for any issues, an exception will occure if the query is incorrect. Note that we need to provide the full package location of our Contract class else JoSQL wouldn't find the class. This can cause a problem if you refactor your code, like move the Contract class to a different package location but don't update the JoSQL query.
  4. The following line we set the :p variable using setVariable method.
  5. We then execute the query and put the results into qr which is an instance of QueryResults.
  6. contractResult will contain the result.
JoSQL uses reflection so "productId" in the query is a getter method like "getProductId()" on the Contract class.

1 comment:

Timo Westkämper said...

For a typesafe alternative to do LINQ-like queries on Java, consider Querydsl :

http://source.mysema.com/display/querydsl/Querydsl

Querydsl supports JPA/Hibernate, JDO, SQL and Collections.