JPA - Like Keyword



Like keyword is used with Where clause in a query to filter out records based on similar items.

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

Example - Usage of Like keyword using JPA

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

LikeDemo.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 LikeDemo {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();

      //Like
      Query query = entitymanager.createQuery("Select e " + "from Employee e " + "where e.ename LIKE 'M%'");
      
      List<Employee> list1=(List<Employee>)query.getResultList( );
      
      for( Employee e:list1 ) {
         System.out.print("Employee ID :"+e.getEid( ));
         System.out.println("\t Employee name :"+e.getEname( ));
      }
   }
}

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 :1202	 Employee name :Manisha
Employee ID :1203	 Employee name :Masthanvali
Advertisements