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

Other Cases: element, map-key-many-to-many, and More

element, like property, can be given the evaluated value of any valid formula expression.



The usage of formula with map-key-many-to-many is similar to that of map-key. However, map-key-many-to-many is usually used in a ternary relationship, where a map key is a referenced object itself, rather than a referenced attribute.

However, there are cases where formula is not supported. Some databases (e.g., Oracle 7) do not support embedded select statements (i.e., a select SQL embedded in the select part of an SQL statement), and in these cases a formula used as evaluation result is not supported. Therefore, you need to first check whether embedded select SQL statements are supported.

Since the SQL that results from Hibernate's mappings takes the formula expression as part of its select target, knowing the SQL dialect of your database will help enrich your use of formula, though it may reduce code portability.

Category 2: Using a formula for Joining

many-to-one

Another common scenario in real-world data models is proprietary relationship mapping, meaning mappings other than the basic one-to-one, one-to-many, and many-to-many relationships. formula is one of the elements provided for this kind of proprietary relationship management. Figure 5 shows an example in which one company can have many contact persons, but only one of them is the default contact person. One company having many contact persons is a typical one-to-many relationship. However, in order to identify the default contact person, the ContactPerson table uses an attribute defaultFlag (where 1 is yes and 0 is no).


Figure 5. User role data schema


Figure 6. User role object model

In order to interpret default contact person relationship into the object model (Figure 6), we use the following mapping:


<hibernate-mapping>
  <class name="Company" table="Company">
    <id name="id" />
    <many-to-one 
      name="defaultContactPerson" 
      property-ref="defaultContactPerson">
        <column name="id"/>
        <formula>1</formula>
        </many-to-one>
  </class>
  <class name="Person" >
    <id name="id" />
    <properties name="defaultContactPerson">
        <property name="companyID" />
        <property name="defaultFlag" />
    </properties>
  </class>
</hibernate-mapping>

Above, we group companyID and defaultFlag in a properties element with the name defaultContactPerson, which forms a unique key of the Person table. The many-to-one element inside of the Company class joins on the defaultContactPerson properties element in the Person class. The resulting SQL will be something like:

select c.id, p.id from Company c, Person p where p.companyID=c.id and p.defaultFlag=1

Pages: 1, 2, 3, 4

Next Pagearrow