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.
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 ( 0 , 2 ) ; //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 }