Hibernate Named Query
1) While executing either HQL, NativeSQL Queries if we want to execute the same queries for multiple times and in more than one client program application then we can use the NamedQueries mechanism.
2) In this Named Queries concept, we use some name for the query configuration, and that name will be used when ever the same query is required to execute.
3) In hibernate mapping file we need to configure a query by putting some name for it and in the client application, we need to use getNamedQuery() given by session interface, for getting the Query reference and we need to execute that query by calling list().
4) If you want to create Named Query then we need to use query element in the hibernate mapping file
Syntax Of hibernate mapping file
<hibernate-mapping>
<class name="---" table="---">
<id name="---" column="---" />
<property name="---" column="---" length="10"/>
<property name="---" column="---" />
--- --- --- ---
</class>
<query name="Give Query Name">
<![CDATA[from Entity e where e.id = :javaPlanet]]>
</query>
</hibernate-mapping>
Read me :
See the <query></query> tag in above file this is the new element we have to add to work
with Named Queries there colon (:) javaPlanet is the label, we will pass the value into that label in the run time.., or let us see the client program logic too
How to Use?
Query query = session.getNamedQuery(" Name given in hibernate mapping xml file ");
query.setParameter("javaPlanet",new Integer(11));
List list = query.list();
In first line we are getting the query from hibernate mapping file to our client program
In Second line we are passing run time value to that query
In Third line we are calling list() method to execute the query