ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Hibernate 3 Formulas
Pages: 1, 2, 3, 4

If the formula expression evaluation result is 0--i.e., no sub-product is allowed--then the object will be of the class Product. If the result is 1, the object will be a NestedProduct. In tables 1 and 2, for the first record (ProductID=10000001) in the Product table, the initialized class will be a NestedProduct because it references a ProductRelease record with SubProductAllowable=1. For the second record (ProductID=20000001) in the Product table, the initialized class will be Product, because it references a ProductRelease record with SubProductAllowable=0.

S/N ProductReleaseID SubProductAllowable ...
1 11 1 ¡­
2 601 0 ¡­
Table 1. Records in the ProductRelease Table

S/N ProductID ProductReleaseID ...
1 10000001 11 ¡­
2 20000001 601 ...
Table 2. Records in the Product Table

Property

A formula inside of a property element allows object attributes to contain certain derived values, like the results of sum, average, max, etc., as in:



<property name="averagePrice" formula="(select avg(pc.price) from PriceCatalogue pc, SelectedItems si where si.priceRefID=pc.priceID)"/>

Furthermore, a formula can also help retrieve values from another table based on certain attribute values for the current record. For example:

<property name="currencyName" formula="(select cur.name from currency cur where cur.id= currencyID)"/>

This helps retrieve a currency name from the currency table. As you can see, these direct mappings can eliminate a lot of conversion coding.

map-key

formula allows map-key to have any possible value. In the following example (Figure 3), we want Role_roleID to be the map-key of the object model (Figure 4).

User Role Data Schema
Figure 3. User role data schema

User Role Object Model
Figure 4. User role object model

In the data schema above, User and Role are linked via a many-to-many relationship table called User_has_Role. In order to get a User with all of the roles assigned to it, we use the following mapping:


<hibernate-mapping>
  <class name="User">
    <id name="userID"/>
    <map name="roles"  
        table="UserRole"/>
      <key column="User_userID"/>
      <map-key 
        formula="Role_RoleID" 
        type="string"/>
      <many-to-many 
        column="Role_RoleID"
        class="Role"/>
    </map>
  </class>
  <class name="Role">
    <id name="roleID"/>
  </class>
</hibernate-mapping>

Role_RoleID is used as the joining column value of the many-to-many element. However, Hibernate does not allow Role_RoleID to be in the column attributes of both map-key and many-to-many. But with a formula, Role_RoleID can be used for map-key as well.

Pages: 1, 2, 3, 4

Next Pagearrow