hibernate 拦截器和事件框架


注册监听器:

MyPreInsertListener.java:

package eventListener;

import org.hibernate.event.PreInsertEvent;
import org.hibernate.event.PreInsertEventListener;

import basicCar.bean.Account;


public class MyPreInsertListener implements PreInsertEventListener {

	public boolean onPreInsert(PreInsertEvent event) {
		Object ob = event.getEntity();
		if (ob instanceof Account) {
			Account bc = (Account) ob;
			if (bc.getOpendate() == null)
				System.out
						.println("the date value is null, i won't insert this!!");
			return true;
		}
		return false;
	}

}


MyLoadListener.java:

package eventListener;

import org.hibernate.HibernateException;
import org.hibernate.event.LoadEvent;
import org.hibernate.event.LoadEventListener;
import org.hibernate.event.def.DefaultLoadEventListener;

import basicCar.bean.Account;




public class MyLoadListener extends DefaultLoadEventListener {
	public void onLoad(LoadEvent event, LoadEventListener.LoadType loadType)
			throws HibernateException {

		System.out.println("entityName:" + event.getEntityClassName()+"  id: "+event.getEntityId());
		
		super.onLoad(event, loadType);
		
		if (event.getEntityClassName().equals("basicCar.bean")) {
			Account bc = (Account) event.getResult();
			if (bc != null && bc.getOpendate()== null) {
				System.out.println("自定义的load事件: 没有日期,不要");
				throw new HibernateException("自定义的load事件: 实体没有日期,抛出异常");
			}

		}
	}
}



下面的代码为load和pre-insert事件注册了两个监听器:

MyLoadListener mll = new MyLoadListener();
		MyPreInsertListener mpl = new MyPreInsertListener();
		cfg.setListener("load", mll);
		cfg.setListener("pre-inset",mpl);

下面是为某个事件注册多个监听器的方法:

LoadEventListener[] stack = {new MyLoadListener(),new DefaultLoadEventListener()};
		cfg.setListener("load", stack);


拦截器:

1.日志记录拦截器:

session范围的:

void saveEntity() {
		
		Session session;
		session = sf.openSession(new LogInterceptor());
myfile.dat:

2 Nov 2012 02:15:33 GMT: save  name: basicCar.bean.Account  id: 56
2 Nov 2012 02:15:33 GMT: save  name: basicCar.bean.Account  id: 57
2 Nov 2012 02:15:33 GMT : update name: basicCar.bean.Customer  id: 299
creations:2,Updates:1,Loads:14



sessinfactory范围的:

使用这个sessionfactory所建立的所有sessin都将使用这个拦截器

void DoConfiguration() {
		// new a configuration and read the configuration from the given path
		cfg = new Configuration();
		cfg.configure("/basicCar/hibernate.cfg.xml");
		// use the properites in the configure file to new a sessionFactory
		sf = cfg.setInterceptor(new LogInterceptor()).buildSessionFactory();
	}
2.实现属性检查修改拦截器:



复合拦截器:

LogInterceptor.java:

package interceptor;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Transaction;
import org.hibernate.type.Type;

import basicCar.bean.Customer;



public class LogInterceptor extends EmptyInterceptor {

	private int updates;
	private int creates;

	private int loads;

	public void onDelete(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {

		Date d = new Date(System.currentTimeMillis());
		String content = d.toGMTString() + ": delete  name: "
				+ entity.getClass().getName() + "  id: " + id;
		FileLog fl = new FileLog(content);
	}

	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
System.err.println("!!!  some dirty !!!");
		updates++;
		Date d = new Date(System.currentTimeMillis());
		String content = d.toGMTString() + " : update name: "
				+ entity.getClass().getName() + "  id: " + id;
		FileLog fl = new FileLog(content);
		for (int i = 0; i < propertyNames.length; i++) {
			System.out.println(propertyNames[i] + ": " + previousState[i]
					+ "; " + currentState[i]);
		}
		System.out.println("??true??n or false   ");

		return false;
	}

	public boolean onLoad(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {

		loads++;

		return true;
	}

	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		System.out.println("onsave2");
		creates++;
		Date d = new Date(System.currentTimeMillis());
		String content = d.toGMTString() + ": save  name: "
				+ entity.getClass().getName() + "  id: " + id;
		FileLog fl = new FileLog(content);
		/*if (entity instanceof BasicCar) {
			for (int i = 0; i < propertyNames.length; i++) {

				if ("date".equals(propertyNames[i])&&state[i]!=null) {
					System.out.println(propertyNames[i] + ":statenull " + state[i]);
					state[i] = new Date(System.currentTimeMillis());
					return true;
				}
			}
		}*/
		if (entity instanceof Customer) {
			for (int i = 0; i < propertyNames.length; i++) {

				if ("salesname".equals(propertyNames[i])) {
					System.out.println(propertyNames[i] + ":salesname!!@@ " + state[i]);
					state[i] = "PPPPPP";
					return true;
				}
			}
		}
		System.out.println();

		return false;
	}

	public void afterTransactionCompletion(Transaction tx) {
		if (tx.wasCommitted()) {
			String content = "creations:" + creates + ",Updates:" + updates
					+ ",Loads:" + loads;
			System.out.println("creations:" + creates + ",Updates:" + updates
					+ ",Loads:" + loads);
			FileLog fl = new FileLog(content);
		}
		updates = 0;
		creates = 0;
		loads = 0;
	}
	public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException 
	{
		System.out.println("collection!!!!!!!!"+collection.getClass().getName());
	}
	public String onPrepareStatement(String arg0) {
		String sqlString=arg0;
		
	//	  System.out.println("log       "+sqlString);
		
	        return sqlString;
	}
	public String getEntityName(Object arg0) throws CallbackException {
		
		return null;
	}
}


MyInterceptor.java:

package interceptor;

import java.io.Serializable;
import java.sql.Date;

import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import basicCar.bean.Account;



public class MyInterceptor extends EmptyInterceptor {

	public boolean onSave(Object entity, Serializable id, Object[] state,
				String[] propertyNames, Type[] types) {
		System.out.println("onsave");
			if (entity instanceof Account) {
				for (int i = 0; i < propertyNames.length; i++) {
					if ("date".equals(propertyNames[i])&&state[i]!=null) {
						System.out.println(propertyNames[i] + ":::" + state[i]);
						state[i] = new Date(System.currentTimeMillis());
						System.out.println(propertyNames[i] + ":##::" + state[i]);
						return true;
					}
				}
			}
			return false;
		}
	public String onPrepareStatement(String arg0) {
		String sqlString=arg0;
		
		 // System.out.println("my       "+sqlString);
		
	        return sqlString;
	}
public String getEntityName(Object arg0) throws CallbackException {
		
		return null;
	}
	}




ChainedInterceptor.java:

package interceptor;

import java.io.Serializable;
import java.util.Iterator;

import org.hibernate.CallbackException;
import org.hibernate.EntityMode;
import org.hibernate.Interceptor;
import org.hibernate.Transaction;
import org.hibernate.type.Type;

/**
 * Implementation of the Hibernate <code>Interceptor</code> interface that
 * allows the chaining of several different instances of the same interface.
 * 
 * @author Laurent RIEU
 * @see Interceptor
 */
public class ChainedInterceptor implements Interceptor {
	// Interceptors to be chained
	private Interceptor[] interceptors;

	public ChainedInterceptor() {
		super();
	}

	public ChainedInterceptor(Interceptor[] interceptors) {
		super();
		this.interceptors = interceptors;
	}

	public boolean onLoad(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) throws CallbackException {
		boolean result = false;
		for (int i = 0; i < interceptors.length; i++) {
			if (interceptors[i].onLoad(entity, id, state, propertyNames, types)) {
				result = true;
			}
		}
		return result;
	}

	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) throws CallbackException {
		boolean result = false;
		for (int i = 0; i < interceptors.length; i++) {

			if (interceptors[i].onFlushDirty(entity, id, currentState,
					previousState, propertyNames, types)) {

				result = true;
			}
		}
		return result;
	}

	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) throws CallbackException {
		System.out.println("onsave3");
		boolean result = false;
		for (int i = 0; i < interceptors.length; i++) {
			if (interceptors[i].onSave(entity, id, state, propertyNames, types)) {
				result = true;
			}
		}
		return result;
	}

	public void onDelete(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) throws CallbackException {
		for (int i = 0; i < interceptors.length; i++) {
			interceptors[i].onDelete(entity, id, state, propertyNames, types);
		}
	}

	public void preFlush(Iterator entities) throws CallbackException {
		for (int i = 0; i < interceptors.length; i++) {
			interceptors[i].preFlush(entities);
		}
	}

	public void postFlush(Iterator entities) throws CallbackException {
		for (int i = 0; i < interceptors.length; i++) {
			interceptors[i].postFlush(entities);
		}
	}

	public Boolean isTransient(Object entity) {
		Boolean result = false;
		for (int i = 0; i < interceptors.length; i++) {
			result = interceptors[i].isTransient(entity);
			if (result != null) {
				result=true;
			}
		}
		return result;
	}


	static int l = 0;

	public int[] findDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		
		//这里必须初始化为空,否则其内里interceptor的任何改变都会被改回去
		int[] result = {};
		
		boolean someDirty = onFlushDirty(entity, id, currentState,
				previousState, propertyNames, types);
		if (someDirty == false)
			return result;

		if (l < interceptors.length) {
			result = interceptors[l].findDirty(entity, id, currentState,
					previousState, propertyNames, types);
			l++;
			return result;
		}
		l = 0;

		return result;
	}

	static int m = 0;

	public Object instantiate(String entityName, EntityMode entityMode,
			Serializable id) throws CallbackException {
		Object result = null;
		if (m < interceptors.length) {
			result = interceptors[m].instantiate(entityName, entityMode, id);
			m++;
			return result;
		}
		m = 0;
		return result;
	}

	public Interceptor[] getInterceptors() {
		return interceptors;
	}

	public void setInterceptors(Interceptor[] interceptors) {
		this.interceptors = interceptors;
	}

	public void afterTransactionBegin(Transaction arg0) {
		for (int i = 0; i < interceptors.length; i++) {
			interceptors[i].afterTransactionBegin(arg0);
		}
	}

	public void afterTransactionCompletion(Transaction arg0) {
		for (int i = 0; i < interceptors.length; i++) {
			interceptors[i].afterTransactionCompletion(arg0);
		}

	}

	public void beforeTransactionCompletion(Transaction arg0) {
		for (int i = 0; i < interceptors.length; i++) {
			interceptors[i].beforeTransactionCompletion(arg0);
		}
	}

	static int n = 0;

	public Object getEntity(String arg0, Serializable arg1)
			throws CallbackException {
		Object entity = null;
		if (n < interceptors.length) {
			entity = interceptors[n].getEntity(arg0, arg1);
			n++;
			return entity;
		}
		n = 0;
		return entity;
	}

	static int i = 0;

	public String getEntityName(Object arg0) throws CallbackException {
		String entityName = null;
		if(i < interceptors.length) {
			entityName = interceptors[i].getEntityName(arg0);
			i++;	
			return entityName;		
		}
		i=0;
		return entityName;
	}

	public void onCollectionRecreate(Object arg0, Serializable arg1)
			throws CallbackException {
		for (int i = 0; i < interceptors.length; i++) {
			interceptors[i].onCollectionRecreate(arg0, arg1);
		}
	}

	public void onCollectionRemove(Object arg0, Serializable arg1)
			throws CallbackException {
		for (int i = 0; i < interceptors.length; i++) {
			interceptors[i].onCollectionRemove(arg0, arg1);
		}
	}

	public void onCollectionUpdate(Object arg0, Serializable arg1)
			throws CallbackException {
		for (int i = 0; i < interceptors.length; i++) {
			interceptors[i].onCollectionUpdate(arg0, arg1);
		}

	}

	static int k = 0;

	public String onPrepareStatement(String arg0) {
		String sqlString = arg0;
		if (k < interceptors.length) {
			sqlString = interceptors[k].onPrepareStatement(sqlString);
			k++;
			return sqlString;
		}
		System.out.println("kkk  != null " + k + "  " + sqlString);
		k = 0;
		return sqlString;
	}
}
 



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Struts2 是一个开源的 Java Web 框架,用于构建企业级应用程序。它提供了一组用于简化 Web 应用程序开发的工具和框架Hibernate 是一个开源的 Java 持久层框架,用于简化数据库操作。它提供了一组用于管理数据库实体对象的工具和框架。 struts2+hibernate项目是用struts2来构建前端界面,用hibernate来管理数据库交互的项目。 ### 回答2: Struts2和Hibernate都是常用的Java开发框架,可以通过结合使用来构建Web应用程序。 Struts2是一个基于MVC设计模式的框架,它将应用程序分成三个部分:模型(Model)、视图(View)和控制器(Controller)。在Struts2中,模型表示数据,视图定义了如何呈现数据,控制器负责处理用户的请求并更新模型和视图。通过使用Struts2,可以将业务逻辑与视图分离,提高代码的可维护性和可重用性。 Hibernate是一个开源的对象关系映射(ORM)框架,它提供了一种将对象模型映射到关系数据库的机制,从而实现对数据库的访问和操作。使用Hibernate,开发人员可以通过简单的配置文件描述对象和数据库表之间的映射关系,Hibernate会自动执行SQL语句并将结果映射回Java对象。通过使用Hibernate,可以简化数据库访问的过程,提高开发效率。 在一个项目中同时使用Struts2和Hibernate可以发挥它们各自的优势。Struts2可以负责用户请求的处理和页面的呈现,而Hibernate可以负责数据的持久化和访问。使用Struts2和Hibernate,可以将应用程序分成多个模块,每个模块负责特定的功能,进一步提高代码的可维护性和可重用性。 总结而言,Struts2和Hibernate是两个功能强大的Java开发框架,可以互补使用来构建高效且易于维护的Web应用程序。 ### 回答3: Struts2和Hibernate是常用于开发Java Web应用的两个框架。它们分别负责解决Web层和持久层的问题。 Struts2是一个基于MVC(Model-View-Controller)架构的Web框架,用于处理Web层的业务逻辑。它通过将请求和响应分派给相应的Action类来处理用户的请求。Struts2提供了丰富的标签库和拦截器机制,使开发人员可以轻松地实现表单验证、权限控制、数据封装等公共功能。此外,Struts2采用了面向对象的设计思想,开发者可以通过自定义Action类和拦截器来实现更加灵活和可扩展的功能。 Hibernate是一个优秀的对象关系映射(ORM,Object-Relational Mapping)框架,用于解决持久层的问题。它将Java对象和数据库表之间的映射关系进行了封装,并提供了一系列API供开发人员操作数据库。使用Hibernate,开发者可以通过对象的方式操作数据库,而无需编写复杂的SQL语句。Hibernate还提供了缓存和事务管理等功能,用于提高数据访问的性能和可靠性。 结合使用Struts2和Hibernate可以将Web层和持久层完美地结合在一起。Struts2负责用户请求的处理和业务逻辑的控制,而Hibernate负责数据库的操作和数据的持久化。开发人员只需在Struts2的Action类中调用Hibernate的API,即可完成数据的读取、插入、更新和删除等操作。通过这种方式,开发人员可以专注于业务逻辑的实现,而无需关注底层的数据库细节。这种结合使用的方式可以极大地提高开发效率,并且使代码的维护更加方便。最重要的是,使用Struts2和Hibernate可以使应用的开发变得更加规范和模块化,提高了代码的可重用性和可测试性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值