• Entries (RSS)
  • Comments (RSS)

JoSQL (SQL for Java Objects)

Posted by | Posted in Java | Posted on 30-06-2008

Tagged Under : ,

Recently I made a post on Language Integrated Query (LINQ) in C#. Since I like that feature very much I did a search for finding some similar libraries for Java. There is one project in sourceforge called JoSQL (http://josql.sourceforge.net/index.html) for querying collections using SQL syntax in Java. I would call JoSQL as LINQ alternative for Java. This JoSQL (SQL for Java Objects) is a small and powerful library which helps us to query Java collections. I just completed a small program for sorting a collection of object. Yes there are some Out of the Box sorting functions available in Collections. But still I used JoSQL for my sorting purpose.

Here is my first JoSQL program.

		// Create a list first
		ArrayList list = new ArrayList();
		// Add something to our collection
		// Just print it.
		// Create the query object.
		Query qry = new Query();
		// Our Java Object SQL for getting all the elements that are greater than
		// 2 and sorted based on the value
		qry.parse("SELECT * FROM java.lang.String WHERE toString > 2 ORDER BY toString ");
		// Get the query results.
		List results = qry.execute(list).getResults();
		// Now display the query results
		for(int index=0; index < results.size(); index++){

I will give a small explanation for the above program. First I am creating an ArrayList and populating the collection with some values. Next I am querying on that collection. The query I used is “SELECT * FROM java.lang.String WHERE toString > 2 ORDER BY toString “. Here just like a normal SQL our JoSQL query also started with a SELECT, then the columns we want(In my case I want all the columns so I used *). Then I have mentioned java.lang.String as my FROM. This is because my Collection contains String objects. Then the WHERE clause. The WHERE clause condition in our case is ‘toString > 2’. Here toString is a method inside java.lang.String class. I wanted some column to apply my condition, so I thought I will use the toString method as my column name. Instead of toString method we can use any method we want. Then the ORDER BY clause. There also I used the toString methods as I did not find any other column to sort :-)


Read More

Post a Comment