0
Sponsored Links


Ad by Google
Now the named query. In my previous post, I have shared with you native query example here and How to use Criteria Query in Hibernate at Criteria Query Example. But Named Query is totally different than all these, SQL Query and HQL Query.
What is Named Query : 
Named Query is not a special query, It's just a way of placing your common queries at a single destination just like we put some constants in a enum or a single constant file which will help us to mange the things. The same way named query is just a way of putting the sql/hql query to single destination so that you can easily manage them at any point, and named queries are used by calling their name.

How To Use Named Query:
To use named query you need to define named queries in your mapped hbm.xml file or annotated pojo class, and then you need to call them by their name as the way you used in query with session.

Syntax to defines named query in annotated java class.
@NamedQueries({@NamedQuery(name = "", query = "")})

Or if it's native named query than,
@NamedNativeQueries({ @NamedNativeQuery(name = "", query = "", resultClass = *.class) })

OK, Now move with a practical example of using Named Query. In this tutorial, I am going to use the same classes which I used at Query Cache Example.

Tools and Technologies, I am using here:

  • JDK 7
  • Hibernate 4.3.7
  • MySql 5.1.10
  • Eclipse Juno 4.2
  • Maven 3.2

Step 1. Create Database script
CREATE DATABASE ;

USE `hibernate_tutorial`;

/*Table structure for table `country` */

DROP TABLE IF EXISTS `country`;

CREATE TABLE `country` (
  `country_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `country_code` varchar(255) DEFAULT NULL,
  `country_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`country_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
Step 2. Create annotated Country.java: This class defines named queries
package com.javamakeuse.poc.pojo;

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

@Entity
@Table(name = "country")
// named queries
@NamedQueries({
  @NamedQuery(name = "getAllCountries", query = "from Country c"),
  @NamedQuery(name = "getCountryById", query = "from Country c where c.countryID = :countryID") })
// native named query
@NamedNativeQueries({ @NamedNativeQuery(name = "getCountryByNativeNamedQuery", query = "select * from country c where c.country_id = :countryID", resultClass = Country.class) })
public class Country {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "country_id")
 private long countryID;

 @Column(name = "country_name")
 private String countryName;

 @Column(name = "country_code")
 private String countryCode;

 public Country() {
 }

 public Country(String countryName, String countryCode) {
  super();
  this.countryName = countryName;
  this.countryCode = countryCode;
 }

 public String getCountryName() {
  return countryName;
 }

 public String getCountryCode() {
  return countryCode;
 }

 @Override
 public String toString() {
  return "Country [countryID=" + countryID + ", countryName="
    + countryName + ", countryCode=" + countryCode + "]";
 }

}

Above, I defines named query and native named query.

Step 3. Create HibernateUtility.java class to build SessionFactory
package com.javamakeuse.poc.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtility {
 private static final SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory() {
  Configuration configuration = new Configuration();
  configuration.configure();

  ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
    .applySettings(configuration.getProperties()).build();
  SessionFactory sessionFactory = configuration
    .buildSessionFactory(serviceRegistry);
  return sessionFactory;
 }

 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}
Step 4. Create hibernate.cfg.xml file
<?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">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_tutorial</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
         
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping class="com.javamakeuse.poc.pojo.Country"/>
          
    </session-factory>
</hibernate-configuration>

Step 5. Create Main.java class to call named query.
package com.javamakeuse.poc.service;

import java.util.List;

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

import com.javamakeuse.poc.pojo.Country;
import com.javamakeuse.poc.util.HibernateUtility;

public class Main {
 public static void main(String[] args) {
  System.out.println("Country size is - " + getAllCountry().size());
  System.out.println("Country Details - " + getCountry(1));
  System.out.println("Country Details By NativeNamedQuery - "
    + getCountryByNativeNamedQuery(1));
 }

 public static Country getCountry(long id) {

  Session session = HibernateUtility.getSessionFactory().openSession();

  Query query = session.getNamedQuery("getCountryById");
  query.setParameter("countryID", id);

  return query.list() == null ? null : (Country) query.list().get(0);

 }

 public static Country getCountryByNativeNamedQuery(long id) {

  Session session = HibernateUtility.getSessionFactory().openSession();

  Query query = session.getNamedQuery("getCountryByNativeNamedQuery");
  query.setParameter("countryID", id);

  return query.list() == null ? null : (Country) query.list().get(0);

 }

 public static List<Country> getAllCountry() {

  Session session = HibernateUtility.getSessionFactory().openSession();

  Query query = session.getNamedQuery("getAllCountries");
  return query.list();

 }
}


OUT PUT:
Hibernate: 
    select
        country0_.country_id as country_1_0_,
        country0_.country_code as country_2_0_,
        country0_.country_name as country_3_0_ 
    from
        country country0_
Country size is - 2
Hibernate: 
    select
        country0_.country_id as country_1_0_,
        country0_.country_code as country_2_0_,
        country0_.country_name as country_3_0_ 
    from
        country country0_ 
    where
        country0_.country_id=?
Hibernate: 
    select
        country0_.country_id as country_1_0_,
        country0_.country_code as country_2_0_,
        country0_.country_name as country_3_0_ 
    from
        country country0_ 
    where
        country0_.country_id=?
Country Details - Country [countryID=1, countryName=Australiya, countryCode=+61]
Hibernate: 
    select
        * 
    from
        country c 
    where
        c.country_id = ?
Hibernate: 
    select
        * 
    from
        country c 
    where
        c.country_id = ?
Country Details By NativeNamedQuery - Country [countryID=1, countryName=Australiya, countryCode=+61]


To create step by step project using maven + eclipse you can follow my this tutorial

That's it :)

Download the complete example from here


Sponsored Links

0 comments:

Post a Comment