Hibernate Named Query Introduction Tutorial
Let us see few points, before going to see an example on Named Queries in HIbernate..
- 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 Named Queries mechanism
- 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
- 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()
- If you want to create Named Query then we need to use query element in the hibernate mapping file
Syntax Of hibernate mapping file [For HQL]
1234567891011121314<hibernate-mapping> <class name="---" table="---"> <id name="---" column="---" /> <property name="---" column="---" length="10"/> <property name="---" column="---" /> --- --- --- --- </class>
<query name="Give Query Name">
<![CDATA[from Product p where p.price = :java4s]]>
</query>
</hibernate-mapping>
Notes:
- See line numbers 10,11,12, this is the new element we have to add to work with Named Queries
- there colon (:) java4s is the label, i will pass the value into that label in the run time.., or let us see the client program logic too
Example Logic in Application:
123Query qry = session.getNamedQuery("Name we given in hibernate mapping xml"); qry.setParameter("java4s",new Integer(1022)); List l = qry.list();
Notes:
- Line number 1, getting the query from hibernate mapping file to our client program
- Line number 2, passing run time value to that query
- Line number 3, calling list() method to execute the query
Up to now this is the case if we use HQL query in hibernate mapping file, let us see the case if we would like to use nativeSQL query
Syntax Of hibernate mapping file [For Native SQL]
1234567891011121314<hibernate-mapping> <class name="---" table="---"> <id name="---" column="---" /> <property name="---" column="---" length="10"/> <property name="---" column="---" /> --- --- --- --- </class>
<sql-query name="Give Query Name">
select * from PRODUCTS
</sql-query>
</hibernate-mapping>
Notes:
- If we want to give HQL query in hiberante mapping file, we need to use <query/> element, but we have to use <sql-query /> element in case of Native SQL
- See line number 11, its the normal sql command, and PRODUCTS is the table name, not the pojo class name ?
Done…!!!!!
post a comment