Named Query In Hibernate

Q. What is named query in hibernate? Example of the named query using annotation?

Steps to run below example –

Step 1 – Create a java project(Since we are not using maven for jar/library, need to download the jar and add manually in the project)

Step 2 – Download hibernate jar and add it to project( right-click on project/properties/java build path/libraries/add external jars/ browse and add).

Step 3 – define the below classes and run the main class(Don’t forget to change the username and password in hibernate.cfg.xml for the database, that you have given during installation of Oracle in your machine ).

Let’s see a simple example for the named query using annotation.

Book.java – 

package namedquery;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQuery;

@Entity
@NamedQuery(name = "Book.byId", query = "from Book where bookId=?")
@NamedNativeQuery(name = "Book.byName", query = "select * from Book where book_Name=?", resultClass = Book.class)
public class Book {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int bookId;

	@Column(name = "book_name")
	private String bookName;

	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

}

hibernate.cfg.xml – 

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">SYSTEM</property>
<property name="connection.password">oracle</property>
 
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
 <mapping class="namedquery.Book" />

 
</session-factory>
</hibernate-configuration>

NamedQueryExample.java  – 

package namedquery;



import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class NamedQueryExample {
	public static void main(String[] args) {
		SessionFactory factory = null;
		Session session = null;
		Configuration configuration = new Configuration().configure();
		try {

			factory = configuration.buildSessionFactory();
			session = factory.openSession();
			Transaction tx = session.beginTransaction();
			Query query=session.getNamedQuery("Book.byId");
			query.setInteger(0,1);

			List<Book> bookList=(List<Book>)query.list();
			for(Book bl:bookList) {
				System.out.println(bl.getBookName() +"---"+bl.getBookId());
			}
			Query query1=session.getNamedQuery("Book.byName");
			query1.setString(0,"half girlfriend");
			
			System.out.println("by name");
			List<Book> bookList1=(List<Book>)query1.list();
			for(Book b1:bookList1) {
				System.out.println(b1.getBookName() +"---"+b1.getBookId());
			}
			tx.commit();
		
			System.out.println("success");
			

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e);

		} finally {

			session.close();
			factory.close();
		}
	}
}

When you run this program expected output is –