Hibernate Interceptor
Hibernate interceptor allows application to change properties
of a entity object before save, update, delete, or load. It allows to control follow or stop.
Attaching interceptor reference to hibernate session
==============================================
public int additeam(Item item) {
Integer itemCode = 0;
try {
ItemInterceptor itemInterceptor = new ItemInterceptor();
session = sessionFactory.openSession(itemInterceptor);
transaction = session.beginTransaction();
log.info("Before addItem - Dao");
itemCode = (Integer) session.save(item);
transaction.commit();
} catch (HibernateException hibernateException) {
transaction.rollback();
log.info(hibernateException.getMessage());
} finally {
session.close();
}
return itemCode;
}
Hibernate Interceptor - Class Implementation:
=======================================
package com.xyz.interceptor;
import java.io.Serializable;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import com.xyz.dto.Item;
public class ItemInterceptor extends EmptyInterceptor {
/**
* Pedababu M
*/
private static final long serialVersionUID = 1L;
private final Log log = LogFactory.getLog(getClass());
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
log.info("Before the "+entity.getClass()+" onSave....");
log.info("getName "+entity.getClass().getName()+" onSave....");
log.info("getModifiers "+entity.getClass().getModifiers()+" onSave....");
log.info("S ID :" + id);
for (int index = 0; index < state.length; index++) {
log.info(state[index]);
}
//chnaging discount before saving - in interceptor
if (entity instanceof Item) {
((Item) entity).setDiscount(10);
}
return super.onSave(entity, id, state, propertyNames, types);
}
}
onDelete – This method is called before delete entity object
onLoad – This method is called before entity object
initialization.
etc.
Query with parameter
================
List<Item> itemList = null;
Session session = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
Query query =session.createQuery("from Item item where item.itemId=:itemId");
query.setParameter("itemId", itemNo);
itemList =query.list();
log.info("itemList size::::" + itemList.size());
Iterator<Item> it = itemList.iterator();
while (it.hasNext()) {
Item t = it.next();
log.info(t.getItemId() + " " + t.getItemName());
}
} catch(Exception exception){
exception.printStackTrace();
}
finally {
session.close();
}
No comments:
Post a Comment