Friday, 19 October 2012

Hibernate formula attribute

I found it very useful for converting columns of same purpose in different table.For example date table in one table is not in same format compare to the date column in other table.This incompatibility may lead to data access issues.When we try to fetch data through hibernate mapping it won't work as mapping column e.g date is not in same format.formula attribute allows you to declare an arbitrary SQL expression that will be used to evaluate type of row.

e.g.
 <many-to-one name="paymentEntity"
       class="com.test.payment.model.data.bondEntity"
       update="false" insert="false" fetch="select">
       <column name="BANK_NUMBER" length="20" not-null="true"/>
       <column name="ACCOUNT_NUMBER" length="16" not-null="true"/>
       <formula>to_char(PAYMENT_DATE, 'yyyyMMdd')</formula>
 </many-to-one>


Derived properties are by definition read-only. The property value is computed at load time. You declare the computation as an SQL expression. This then translates to a SELECT clause subquery in the SQL query that loads an instance: 

<property name="totalPrice"
  formula="(SELECT SUM (li.quantity*p.price) FROM LineItem li, Product p
                WHERE li.productId = p.productId
                AND li.customerId = customerId
                AND li.orderNumber = orderNumber )"/>