91-9990449935 0120-4256464 |
Hibernate Named QueryThe hibernate named query is way to use any query by some meaningful name. It is like using alias names. The Hibernate framework provides the concept of named queries so that application programmer need not to scatter queries to all the java code. There are two ways to define the named query in hibernate:
Hibernate Named Query by annotationIf you want to use named query in hibernate, you need to have knowledge of @NamedQueries and @NamedQuery annotations. @NameQueries annotation is used to define the multiple named queries. @NameQuery annotation is used to define the single named query. Let's see the example of using the named queries: Example of Hibernate Named Query by annotationIn this example, we are using annotations to defined the named query in the persistent class. There are three files only:
In this example, we are assuming that there is em table in the database containing 4 columns id, name, job and salary and there are some records in this table. Employee.javaIt is a persistent class that uses annotations to define named query and marks this class as entity. hibernate.cfg.xmlIt is a configuration file that stores the informations about database such as driver class, url, username, password and mapping class etc. FetchData.javaIt is a java class that uses the named query and prints the informations based on the query. The getNamedQuery method uses the named query and returns the instance of Query. Hibernate Named Query by mapping fileIf want to define named query by mapping file, you need to use query element of hibernate-mapping to define the named query.
In such case, you need to create hbm file that defines the named query. Other resources are same as given in the above example except Persistent class Employee.java where you don't need to use any annotation and hibernate.cfg.xml file where you need to specify mapping resource of the hbm file. The hbm file should be like this: emp.hbm.xmlThe persistent class should be like this: Employee.javaNow include the mapping resource in the hbm file as: hibernate.cfg.xml
Next TopicCaching In Hibernate
|