Easy learning with example program codes

Hibernate named query using annotation

Named query is a concept of using queries by name. First a query is defined and a name is assigned to it. Then it can be used anywhere by this alias name.

Syntax of hibernate named query using annotation:

    @NamedQuery(name = " queryName ", query = " queryString ")

How to call a named query?

We can call the named query by getNamedQuery() method of Session interface.
Query query = session.getNamedQuery(“queryName”);


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
 * This class represents a persistent class for Student.
 * @author codesjava
        name = "getStudentByRollNo",  
        query = "from Student where rollNo = :rollNo"  
@Table(name= "STUDENT")
public class Student {
	//data members
	private int studentId;
	private String firstName;
	private String lastName;
	private String className;
	private String rollNo;
	private int age;
	//no-argument constructor
	public Student(){
	//getter and setter methods
	@Column(name = "Student_Id", unique = true, nullable = false)
	public int getStudentId() {
		return studentId;
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	@Column(name = "First_Name")
	public String getFirstName() {
		return firstName;
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	@Column(name = "Last_Name")
	public String getLastName() {
		return lastName;
	public void setLastName(String lastName) {
		this.lastName = lastName;
	@Column(name = "Class")
	public String getClassName() {
		return className;
	public void setClassName(String className) {
		this.className = className;
	@Column(name = "RollNo")
	public String getRollNo() {
		return rollNo;
	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	@Column(name = "Age")
	public int getAge() {
		return age;
	public void setAge(int age) {
		this.age = age;


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration SYSTEM
        <property name="dialect">
        <property name="connection.url">
        <property name="connection.username">
        <property name="connection.password">
        <property name="connection.driver_class">
        <property name="">
        <property name="show_sql">
        <mapping class=""/>

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 * This is a utility class for getting the hibernate session object.
 * @author codesjava
public class HibernateUtil {
    private static final SessionFactory sessionFactory = 
    private static SessionFactory buildSessionFactory() {
    	SessionFactory sessionFactory = null;
        try {
        	//Create the configuration object.
        	Configuration configuration = new Configuration(); 
        	//Initialize the configuration object 
                //with the configuration file data
        	// Get the SessionFactory object from configuration.
        	sessionFactory = configuration.buildSessionFactory();
        catch (Exception e) {
        return sessionFactory;
    public static SessionFactory getSessionFactory() {
        return sessionFactory;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.codesjava.persistence.HibernateUtil;
 * This class is used for the hibernate operations.
 * @author codesjava
public class HibernateTest {
     public static void main(String args[]){
         //Create the student object.
         Student student = new Student();
        //Setting the object properties.
        student.setClassName("MCA final");
        //Get the session object.
        Session session = 
        //Start hibernate transaction.
        //Persist the student object.;
        //Commit hibernate transaction.
        //select a student record using named query	
        Query query = session.getNamedQuery("getStudentByRollNo");  
        query.setString("rollNo", "MCA/07/15");
        List<Student> stuList = (List<Student>) query.list();
        for(Student stu : stuList){
            System.out.println("First Name: " + stu.getFirstName());
            System.out.println("Last Name: " + stu.getLastName()); 
            System.out.println("Class: " + stu.getClassName()); 
            System.out.println("RollNo: " + stu.getRollNo()); 
            System.out.println("Age: " + stu.getAge());     
        //Close hibernate session.


Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, Class, 
RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: select student0_.Student_Id as Student1_0_, 
student0_.First_Name as First2_0_, student0_.Last_Name as 
Last3_0_, student0_.Class as Class0_, student0_.RollNo as 
RollNo0_, student0_.Age as Age0_ from Student 
student0_ where student0_.RollNo=?
First Name: Sunil
Last Name: Kunar
Class: MCA final
RollNo: MCA/07/15
Age: 27

Download this example.
Next Topic: Hibernate native SQL with example.
Previous Topic: Hibernate named query using xml with example.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.


Please follow and like us:

Copyright © 2020 CodesJava Protection Status