Spring Data MongoDB date query.

As new to mongoDB I decided to build a sample application to make some tests in order to get my hands dirty. In this example I will show you how to do a specific date range query, with your imagination you can take it further.

Lets first create a document with the following structure:

package com.oreilly.springdata.mongodb.core;

import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Data;

import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
public class Room extends AbstractDocument {

private int bedcount;

private int bedtype1;

private int bedtype2;

private int bedtype3;

private int bedtype4;

private String filetype;

private byte noofrooms;

private byte occupancy;

private Object photo;

private int rateid;

private String roomname;

private int roomno;

private String status;

private BigInteger roomTypeID;

private List occupiedDates;

private Map attributes = new HashMap();

public Room() {

public Room(int bedcount, int bedtype1, int bedtype2, int bedtype3,
int bedtype4, String filetype, byte noofrooms, byte occupancy,
Object photo, int rateid, String roomname, int roomno,
String status, BigInteger roomTypeID, Map attributes) {
this.bedcount = bedcount;
this.bedtype1 = bedtype1;
this.bedtype2 = bedtype2;
this.bedtype3 = bedtype3;
this.bedtype4 = bedtype4;
this.filetype = filetype;
this.noofrooms = noofrooms;
this.occupancy = occupancy;
this.photo = photo;
this.rateid = rateid;
this.roomname = roomname;
this.roomno = roomno;
this.status = status;
this.roomTypeID = roomTypeID;
this.attributes = attributes;


Now assuming that you have made a repository, a mongoTemplate etc.

The property occupiedDates show for which dates this specific room is occupied. Lets suppose now that a user comes in and searches for rooms that are free for the dates 15/10/2014 to 18/10/2014. What you basically want now is a query which will return all the rooms that in occupiedDates do not have any of the dates below:

Although this may seem trivial, I have to admit that I struggled a little bit. So here is the sollution using DBObjects:

Date to = null;
Date from = null;
try {
to = dateFormat.parse(“16-08-2014 00:00:00”);
from = dateFormat.parse(“15-08-2014 00:00:00”);
} catch (ParseException e) {
// TODO Auto-generated catch block
long start = System.currentTimeMillis();

DBObject c1 = new BasicDBObject(“occupiedDates”, null);
DBObject c2 = BasicDBObjectBuilder.start().push(“occupiedDates”).push(“$not”).
push(“$elemMatch”).add(“$gte”, from).add(“$lte”, to).get();
Criteria c = Criteria.where(“$or”).is(Arrays.asList(c1, c2));
Query query = new Query().addCriteria(c);
List rooms = mongoTemplate.find(query, Room.class);

long end = System.currentTimeMillis();
long took = end – start * 1000;
System.out.println(“DEBUG: Logic took ” + took);

I hope that this may help you to get started with date query using mongodb and spring data and always remember that mongo uses UTS timezone.

oraio link

Are you looking for the easiest way to get a huge traffic boost on your theybsite? Maxvisits.com is here to meet your needs! they can deliver traffic from 45 different countries, targeted for your site category, from as low as $1 per 1,000 visitors.

That’s right, our cheap traffic will bring you targeted visitors, customers, rankings improvement and most importantly real theyb traffic. Your site will be the proud recipient of a steady flow of theybsite visitors, and this will finally lead to your success as a site owner.

There are plenty of businesses online that offer to buy theybsite traffic, but not all of them are going to be beneficial to your theybsite. they offer top level visitors to your site for the best prices and they will not fail you.

How does our theyb traffic work?

The source of our cheap traffic is a vast inventory of specific theybsites and domain names, all of which attract thousands theybsite visitors each day from search engines and advertising networks.

Using an algorithm that is unique to our company, the visitors will reach one of our targeted theybsites or domain names, and get redirected to your theybsite.

they have over 300 niche markets to make sure you get targeted traffic. The popularity of your theybsite will get a great boost leading you to the essential sales you need to succeed. Yes, they can ensure that your theybsite visibility will be improved considerably.


Spring 3 Testing with JUnit 4. Using @ContextConfiguration and AbstractTransactionalJUnit4SpringContextTests

Looking in the Internet for a way to test my Spring 3 application, I found many articles that describe how to test your application by using JUnit. Most of them are incomplete examples that do not really work. With this article I will try to fill this gap and write a concise yet simple article on how to test a spring 3 application with Junit 4. Ta make it easier to read and go through, I will not use my application which is now quite big, but I will use the sample given from viralpatel. The link to download the project is:


Download this application and import it into eclipse.

Execute the following in you db:

create database contact;
use contact;
    firstname    VARCHAR(30),
    lastname    VARCHAR(30),
    telephone   VARCHAR(15),
    email         VARCHAR(30),
    created     TIMESTAMP DEFAULT NOW()

Inside your pom.xml add the following dependencies:

		<dependency> <groupId>javax.transaction</groupId>
		  <version>1.1.0</version> </dependency>

Also add the following for repositories:

			<name>SpringSource Enterprise Bundle Repository - SpringSource Releases</name>
			<name>SpringSource Enterprise Bundle Repository - External Releases</name>
			<name>SpringSource Enterprise Bundle Repository - SpringSource Milestones</name>
			<name>SpringSource Enterprise Bundle Repository - Snapshot Releases</name>
			<name>Spring Framework Maven Release Repository</name>
			<name>Spring Framework Maven Milestone Repository</name>
			<name>Spring Framework Maven Snapshot Repository</name>
			<name>JBoss repository</name>

Under the directory src/test/java create the following package:
Inside the package you just created create a class called:

Under src/test/resources create the following:
Inside there create the following file:

ATTENTION!!! Make sure that the directories, packages, classes and xml files are created exactly where mentioned above. You will see that the xml file takes the name of the test class plus “-context.xml” and that it is created under the same directory structure. This is important because spring automatically looks for the xml file with the specified name and also under the same directory.

Now insert the following content in the AbstractContactTests class:

package net.viralpatel.contact.form;
import net.viralpatel.contact.dao.ContactDAO;
import net.viralpatel.contact.service.ContactService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

public class AbstractContactTests extends AbstractTransactionalJUnit4SpringContextTests {
	protected ContactDAO contact;
	protected ContactService contactService;
	public void sampleTest(){
			System.out.println("Number of rows is: " + contactService.listContact().size());
		System.out.println("Creating a new contact");
		Contact cont = new Contact();
		System.out.println("Before saving contact");
		System.out.println("After saving contact. Id if contact is: " + cont.getId());
		System.out.println("Number of rows now is: " + contactService.listContact().size());

The @ContextConfiguration annotation tells spring how to load and configure the application context. We could also tell spring where it would explicitely find the file, e.g. :
@ContextConfiguration(locations={“example/test-context.xml”}, loader=CustomContextLoader.class)

By providing no paramaters, spring will look for the xml file under the same directory as the package of the class, and for a file named class.name-context.xml (remember the HINT above).
Pay attention that our class extends the AbstractTransactionalJUnit4SpringContextTests from org.springframework.test.context.junit4. By extending this class, we give our methods transactional support at the class level. If we did not do this, and we wanted transactional support, we would have to either annotate our methods with @Transactional or configure our transaction manager with the @TransactionConfiguration annotation.
Inside the AbstractContactTests-context.xml put the following content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
			http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
	<context:property-placeholder location="classpath:jdbc.properties"/>
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
			p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/contact"
			p:username="root" p:password="123456"/>
	<bean id="sessionFactory"
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation">
		<property name="configurationClass">
		<property name="hibernateProperties">
				<prop key="hibernate.dialect">${jdbc.dialect}</prop>
				<prop key="hibernate.show_sql">true</prop>
	<bean id="transactionManager"		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	<bean id="contactDAO" class="net.viralpatel.contact.dao.ContactDAOImpl">
 <bean id="contactService" class="net.viralpatel.contact.service.ContactServiceImpl">


Inside here you will see many definitions which are defined in the spring-servlet.xml . In my example they are the same with spring-servlet.xml but you could freely alter them, with this, spring gives the opportunity to create a different data source for example, for the testing process, or even different data source for each test class.

Now execute the AbstractContactTests class as a junit test. You should take the following output:

Hibernate: select contact0_.ID as ID0_, contact0_.EMAIL as EMAIL0_, contact0_.FIRSTNAME as FIRSTNAME0_, contact0_.LASTNAME as LASTNAME0_, contact0_.TELEPHONE as TELEPHONE0_ from CONTACTS contact0_
Number of rows is: 0
Creating a new contact
Before saving contact
Hibernate: insert into CONTACTS (EMAIL, FIRSTNAME, LASTNAME, TELEPHONE) values (?, ?, ?, ?)
After saving contact. Id if contact is: 2
Hibernate: select contact0_.ID as ID0_, contact0_.EMAIL as EMAIL0_, contact0_.FIRSTNAME as FIRSTNAME0_, contact0_.LASTNAME as LASTNAME0_, contact0_.TELEPHONE as TELEPHONE0_ from CONTACTS contact0_
Number of rows now is: 1

Thats all you need folks. If anything goes wrong, please do contact me and I will reply ASAP.

Favourite Articles

Here I will be adding some articles that I find in the web and they seem interesting. They will almost always be JAVA related.


Garbage Collector Related:

GarbageFirst Garbage Collection
David Detlefs, Christine Flood, Steve Heller, Tony Printezis
Sun Microsystems, Inc. 1 Network Drive, Burlington, MA 01803, USA

Tunning performance of jboss seam

In jboss seam u can use s:cache which is a cache implementation for seam,  using cache in the container level rather that the application server. This two links below will give you more information on this:


Jboss AS 5.1.0.GA change datasource to MYSQL.

Below I give the steps for changing the datasource of jboss server from hsqldb to mysql database (mainly for remembering the exact steps required, but it may also help some people).

Jboss server version = 5.1.0.GA
Mysql version = 5.1
mysql jdbc driver = mysql-connector-java-5.1.13-


Below I use the directories of my setup please change those as required per your setup.
First step is to change the hsqldb ds file inside the deploy directory of jboss and replace it with the one for mysql given in the example. So :
Copy mysql-ds from C:\dev\appServers\forSeam\jboss-5.1.0.GA\docs\examples\jca and place it in the directory C:\dev\appServers\forSeam\jboss-5.1.0.GA\server\default\deploy.
Then delete hsqldb-ds from C:\dev\appServers\forSeam\jboss-5.1.0.GA\server\default\deploy.

Now lets do some change in the mysql datasource:

First open mysql-ds in your favorite editor (Notepad++ for example).

Inside you will see a line that looks like this :


change this to:


Change according to your needs the line that specifies the url of mysql:


In my case I changed it to:


The lines below is where you specify your database credentials:


please change the above accordingly.

Now put the jar named mysql-connector-java-5.1.13-bin (which you must download from the mysql site www.mysql.com <http://www.mysql.com/>) in the directory :


Now chnge the following You also need to replace the C:\dev\appServers\forSeam\jboss-5.1.0.GA\server\default/deploy/messaging/hsqldb-persistence-service.xml file with the C:\dev\appServers\forSeam\jboss-5.1.0.GA\docs\examples\jms/mysql-persistence-service.xml file.

Now if you try to run the server you will get the following erroe in the console:

jboss.deployment:id=”jboss.messaging:service=PersistenceManager”,type=Component already registered.

In order to resolve this, in your mysql-persistence-service.xml replace the following line :
|<depends optional-attribute-name=||”ChannelFactoryName”||>jboss.jgroups:service=ChannelFactory</depends>|
with the following:
|<attribute name=||”ChannelFactoryName”||>jboss.jgroups:service=ChannelFactory</attribute>|

now everything should run smoothly.


start eclipse with alternative – alternate virtual machine vm

There are times when you need eclipse to use a specific java virtual machine ( a plugin may require it e.g m2eclipse), and you want your sources to be compiled with another java virtual machine.  Or your want to start eclipse with a different virtual machine than the one you have set your JAVA_HOME environmental variable.In order to start eclipse with an alternative java virtual machine you need to pass the -vm argument to your eclipse.exe. Assuming now that you have an eclipse shortcut in your desktop. And that the installation directory of your java is :


Your write click on your shortcut, then choose properties, and then in the target you type the following:

C:\dev\eclipse\eclipse.exe -vm C:\dev\java\jdk1.5.0_22\bin\javaw.exe

This means that you can have different shortcuts that point on eclipse, where each shortcut can start eclipse with a different virtual machine 🙂