Hibernate

From Guides

Jump to: navigation, search

Contents

External Hibernate Queries

You can externalize your Hibernate queries and put them in your mapping file. I personally use XDoclet2 to generate these mapping files for me. In Hibernate you have the possibility to externalize your hql queries. Here is an example for defining queries within a class.

Mapping:

<hibernate-mapping>
  <class table="your_table" name="your.package.YourClass">
    <id name="yourId" column="your_id">
      <generator class="native"/>
    </id>
    <query name="query_name"><![CDATA[from YourClass]]></query>
  </class>
</hibernate-mapping>

Class:

...
return getSession().getNamedQuery("your.package.YourClass.query_name").list();
...

You could also define queries by putting them outside the class tags. Then your query will be available throughout your application.

XDoclet2

Here are some examples of how to define some Hibernate mappings with XDoclet2.

one-to-many

/**
 * @hibernate.bag
 *  table="table_name"
 *  cascade = "all"
 *  inverse = "true"
 * @hibernate.key
 *  column = "key_id" 
 * @hibernate.one-to-many
 *  class="target.package.YourClass"
 */

many-to-many

/** 
 * @hibernate.bag
 *  table = "your_linking_table"
 *  cascade = "all"
 * @hibernate.key
 *  column = "key_id"
 * @hibernate.many-to-many  
 *  class = "target.package.YourClass"
 *  column = "media_id"
 */
Personal tools
Google Ads