Monday, July 28, 2008

Using BETWEEN in an EJB3 query


Say if you have an EJB3 entity bean named Landmark which is mapped to a table called landmarks which has 2 columns longitude & latitude (amongst others). To query a given latitude & longitude, its a good idea to relax the query a bit by using BETWEEN.



An example is shown below where we allow a tolerance of 0.00003 for both latitude & longitude. The sample shown is an excerpt from an EJB3 entity bean, right before its class declaration.


@Entity
@Table(name = "landmarks")
@NamedQueries( {
@NamedQuery(
name = "Landmark.findByCoordinates",
query = "SELECT lgr FROM Landmark lgr " +
"WHERE lgr.latitude BETWEEN (?1 - 0.00003) AND (?1 + 0.00003) " +
"AND lgr.longitude BETWEEN (?2 - 0.00003) AND (?2 + 0.00003) ")
})
public class Landmark implements Serializable {