Hibernate named query examples
Often times, developer like to put HQL string literals scatter all over the Java code, this method is hard to maintaine and look ugly. Fortunately, Hibernate come out a technique called “names queries” , it lets developer to put all HQL into the XML mapping file or via annotation.
How to declare named query
The named query is supported in both HQL or native SQL. see examples…
1. XML mapping file
HQL in mapping file
<!-- stock.hbm.xml --> <hibernate-mapping> <class name="com.mkyong.common.Stock" table="stock" ...> <id name="stockId" type="java.lang.Integer"> <column name="STOCK_ID" /> <generator class="identity" /> </id> <property name="stockCode" type="string"> <column name="STOCK_CODE" length="10" not-null="true" unique="true" /> </property> ... </class> <query name="findStockByStockCode"> <![CDATA[from Stock s where s.stockCode = :stockCode]]> </query> </hibernate-mapping>
Native SQL in mapping file
<!-- stock.hbm.xml --> <hibernate-mapping> <class name="com.mkyong.common.Stock" table="stock" ...> <id name="stockId" type="java.lang.Integer"> <column name="STOCK_ID" /> <generator class="identity" /> </id> <property name="stockCode" type="string"> <column name="STOCK_CODE" length="10" not-null="true" unique="true" /> </property> ... </class> <sql-query name="findStockByStockCodeNativeSQL"> <return alias="stock" class="com.mkyong.common.Stock"/> <![CDATA[select * from stock s where s.stock_code = :stockCode]]> </sql-query> </hibernate-mapping>
You can place a named query inside ‘hibernate-mapping‘ element, but do not put before the ‘class‘ element, Hibernate will prompt invalid mapping file, all your named queries have to put after the ‘class‘ element.
Regarding the CDATA , it’s always good practice to wrap your query text with CDATA, so that the XML parser will not prompt error for some special XML characters like ‘>’ , <’ and etc.
2. Annotation
HQL in annotation
@NamedQueries({ @NamedQuery( name = "findStockByStockCode", query = "from Stock s where s.stockCode = :stockCode" ) }) @Entity @Table(name = "stock", catalog = "mkyong") 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", catalog = "mkyong") 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");
Conclusion
Named queries are global access, which means the name of a query have to be unique in XML mapping files or 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.








How can resolve @NamedQuery and @NamedNativeQuery? Sounds like the library not exist. Can someone shared the jar library?
Thanks.
org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: could not execute query; uncategorized SQLException for SQL [SELECT nextval('mbmcproperty.property_code_seq') as nextval]; SQL state [25006]; error code [0]; ERROR: cannot execute nextval() in a read-only transaction; nested exception is org.postgresql.util.PSQLException: ERROR: cannot execute nextval() in a read-only transaction
Hi,
could you give us a way to face the NoResultException in case the result of the query is empty ?
Is there a good practice to have ?
Thanks
Just catch the exception or doing a simple empty checking, then return whatever you want :) This is common to handle empty result.
my application related to struts 2.o spring and jpa how can build ant file
my problem is related to @Action and @NameQueries annotations
Hi, i am trying to integrate the Postgres SQL function with Hibernate but i am getting some exception can u just provide me one good example to integrate with Functions and Hibernate…….
What would be the best practice for this case:
I have an Entity names Entity1 and i also want to select a sum() in the query.
select Entity1, sum(anything needed) where ….
I do have to declare a result class so my question is:
How would i handle such a case? Create a class specially for this case?
Thanks for the great tutorials.
Is there anyway I can turn off the update query that goes with select query? To explain, let us say I want to select rows from a table. I use the spring+hibernate so I do getHibernateTemplate().find(“from User where id=?”, new Long(1)). Now, before after I run this query I want to save a User object. It is here in between that Hibernate tries to do an update in the table for the object being saved whose id is not yet created or written to the DB.
Here are the code samples:
In User.hbm.xml
public void save(UploadItem ui){
findByFileSeqNum();
getHibernateTemplate().save(ui);
}
@Transactional(readOnly=true)
public void findByFileSeqNum(){
List cats = getHibernateTemplate().findByNamedQuery(“findUserIdNativeSQL”, new java.lang.Long(1));
Iterator it = cats.iterator();
while(it.hasNext()) {
UploadItem ui2 = (UploadItem)it.next();
}
}
[...] Hibernate named query examples Working with named query in XML file and Annotation. [...]
think there’s something missing
like ACTUALLY EXECUTING THE QUERY!!!!
next time you put up a sampe FINISH IT!!!
you can get it via session.getNamedQuery(“findStockByStockCode”);
To practice more examples, visit here http://www.mkyong.com/tutorials/hibernate-tutorials/
[...] Alternative, you also can use the named query to call your native SQL statement. See Hibernate named query examples here. [...]