Feeds:
Posts
Comments

Archive for December, 2012

register hibernate event listener in applicationContext.xml
<bean id=”sessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
<property name=”configLocation”>
<value>classpath:hibernate.cfg.xml</value>
</property>

<property name=”eventListeners”>
<map>
<entry key=”post-update”>
<bean class=”com.zhengqiucai.UpdateItemListener” />
</entry>
</map>
</property>
</bean>
Image

Event listener implimentation. When a record in the database is updated, onPostUpdate method in this listener class will execute, which will update another field totalCost in this record.

Image

package com.zhengqiucai;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.event.PostUpdateEvent;
import org.hibernate.event.PostUpdateEventListener;
class UpdateItemListener implements PostUpdateEventListener {
public void onPostUpdate(PostUpdateEvent event) {
Session session = event.getSession();//get the session in which the database record is updated.

Item item = (Item) event.getEntity();
float tc = (float) ((item.getPrice() + item.getShippingCost()) * 6.3);
if (item.getTotalCost() != tc) {//to avoid infinite loop of calling the method
try{
//Transaction tx = session.beginTransaction();
item.setTotalCost(tc);
session.update(item);
//tx.commit();
session.flush();//use flush() or the above transaction
}catch(Exception e){
e.printStackTrace();
}

}

}
}

Read Full Post »