tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Hibernate > Native SQL > Entity Query with Parameters

Entity Query with Parameters 

The following example shows how to get entity objects from a native SQL query using addEntity method. Native SQL queries support positional as well as named parameters using setParameter method. Refer first example for the configuration and mapping.

File Name  :  
com/bethecoder/tutorials/hibernate/basic/native_queries/EntityQueryParamsTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.hibernate.basic.native_queries;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;

public class EntityQueryParamsTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    Query query = session.createSQLQuery(
        "SELECT * FROM company where id=? and name=:comp_name"
    ).addEntity(Company.class);
    query.setParameter(02);  //positional parameter
    query.setParameter("comp_name""ABC");  //named parameter
    
    List<Company> companies = query.list();    
    System.out.println("Selected row count : " + companies.size());
    
    for (Company company : companies) {
      System.out.println(company);
    }
    
    session.getTransaction().commit();
    session.close();
  }
  
}
   

It gives the following output,
Selected row count : 1
{ id = 2, name = ABC, employeeCount = 23430, 
	projectCount = 160, address1 = add11, address2 = add22 }



 
  


  
bl  br