JPA - Between Keyword



Between keyword is used with Where clause in a query to filter out records lying between certain range of values.

Following the same example employee management used in previous chapters, we will go through the service classes using between keyword of JPQL.

Example - Usage of Between keyword using JPA

Create a class named BetweenDemo.java under com.tutorialspoint.eclipselink.service package as follows−

BetweenDemo.java

package com.tutorialspoint.eclipselink.service;

import java.util.List;

import com.tutorialspoint.eclipselink.entity.Employee;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;

public class BetweenDemo {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();

      //Between
      Query query = entitymanager.createQuery( "Select e " + "from Employee e " + "where e.salary " + "Between 30000 and 40000" );
      
      List<Employee> list=(List<Employee>)query.getResultList( );

      for( Employee e:list ){
         System.out.print("Employee ID :" + e.getEid( ));
         System.out.println("\t Employee salary :" + e.getSalary( ));
      }
   }
}

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get following result on the console panel of eclipse IDE.

Employee ID :1201	 Employee salary :40000.0
Employee ID :1202	 Employee salary :40000.0
Employee ID :1203	 Employee salary :40000.0
Employee ID :1204	 Employee salary :30000.0
Employee ID :1205	 Employee salary :30000.0
Employee ID :1206	 Employee salary :35000.0
Advertisements