Hibernate Named Query
In the applications, it is usual that a query is used at multiple places. And if the query is huge, it is difficult to maintain the same query without error. To overcome this issue, named query is used. The query is given a name and using that name, it can be used anywhere in the application.
Hibernate framework supports named queries.
There are two ways to define the named query in hibernate:
- by annotation
- by mapping file.
Named Query using Annotation
Named Queries are defines in the following ways at class level. Inside @NamedQueries, multiple queries can be defined using @NamedQuery annotation.
@NamedQueries(
{ @NamedQuery(
name = "myQuery", query = "FROM Employee e where e.name = :name"
)
}
)
Step 1 : Create maven project
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatrainingschool</groupId>
<artifactId>named-query-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Alpha5</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>19.3</version>
</dependency>
</dependencies>
</project>
Step 2 : Create entity class Drink.java
package com.javatrainingschool;
import javax.persistence.Cacheable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@NamedQueries(
{ @NamedQuery(
name = "myQuery", query = "FROM Drink d where d.name = :name"
) }
)
@Entity
@Table(name = "drink_101")
public class Drink {
@Id
private int id;
private String name;
private String type;
private boolean alcoholic;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isAlcoholic() {
return alcoholic;
}
public void setAlcoholic(boolean alcoholic) {
this.alcoholic = alcoholic;
}
@Override
public String toString() {
return "Drink [id=" + id + ", name=" + name + ", type=" + type + ", alcoholic=" + alcoholic + "]";
}
public Drink(int id, String name, String type, boolean alcoholic) {
super();
this.id = id;
this.name = name;
this.type = type;
this.alcoholic = alcoholic;
}
public Drink() {
super();
// TODO Auto-generated constructor stub
}
}
Step 3 : 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="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9iDialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521/xepdb1</property>
<property name="connection.username">singh</property>
<property name="connection.password">azad</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatrainingschool.Drink" />
</session-factory>
</hibernate-configuration>
Step 4 : Create main testing class
package com.javatrainingschool;
import java.util.List;
import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class DrinkMain {
public static void main(String[] args) {
StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
TypedQuery query = session.getNamedQuery("myQuery");
query.setParameter("name", "Cranberry Spritz");
List<Drink> drinks = query.getResultList();
System.out.println("The query has been executed successfully.");
System.out.println(drinks);
session.close();
factory.close();
}
}
Output :