Hibernate Named Query Tutorial with examples

Named queries in hibernate is a technique to group the HQL statements in single location, and lately refer them by some name whenever need to use them. It helps largely in code cleanup because these HQL statements are no longer scattered in whole code.

Advantages of named queries:

below are some minor advantages of named queries:
  1. Fail fast: Their syntax is checked when the session factory is created, making the application fail fast in case of an error.
  2. Reusable: They can be accessed and used from several places which increase re-usability.

How to declare named query in Hibernate using Annotaions

Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.

HQL in annotation

@NamedQueries({
 @NamedQuery(
 name = "findStockByStockCode",
 query = "from Stock s where s.stockCode = :stockCode"
 )
})
@Entity
@Table(name = "stock")
public class Stock implements java.io.Serializable {

// 

}

Native SQL in annotation

@NamedNativeQueries({
 @NamedNativeQuery(
 name = "findStockByStockCodeNativeSQL",
 query = "select * from stock s where s.stock_code = :stockCode",
        resultClass = Stock.class
 )
})
@Entity
@Table(name = "stock")
public class Stock implements java.io.Serializable {
//
}

In native SQL, you have to declare the ‘resultClass‘ to let Hibernate know what is the return type, failed to do it will caused the exception “org.hibernate.cfg.NotYetImplementedException: Pure native scalar queries are not yet supported“.

Call a named query

In Hibernate, you can call the named query via getNamedQuery method.
Query query = session.getNamedQuery("findStockByStockCode").setString("stockCode", "7277");
Query query = session.getNamedQuery("findStockByStockCodeNativeSQL").setString("stockCode", "7277");

Named queries are global access, which means the name of a query have to be unique in annotations. In real environment, it’s always good practice to isolate all the named queries into their own file. In addition, named queries stored in the Hibernate mapping files or annotation are more easier to maintain than queries scattered through the Java code.

Hope we are able to explain you Hibernate Named Query, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.
Hibernate Named Query Tutorial with examples
SHARE
    Blogger Comment
    Facebook Comment