Hibernate的回调与拦截

本文探讨了Hibernate中的回调机制,包括Lifecycle接口的onSave、onUpdate、onDelete和onLoad方法的注意事项,如操作顺序、Session使用限制。同时提到了Validatable接口用于对象校验。此外,还介绍了Hibernate的拦截器Interceptor,推荐使用EmptyInterceptor并强调了线程安全问题。文章建议避免回调和拦截器对POJO的侵入性,以保持代码整洁。
摘要由CSDN通过智能技术生成

在Hibernate中,有两种方式可以捕获实体对象的GRUD操作并执行相应的处理

Hibernate回调(org.hibernate.classic.Lifecycle接口):

//Provides callbacks from the Session to the persistent object.
//Persistent classes may implement this interface but they are not
//required to.
//If a CallbackException is thrown, the operation is vetoed and the
//exception is passed back to the application.
public interface Lifecycle {
	
	//If onSave(), onUpdate() or onDelete() return VETO,
	//the operation is silently vetoed.
	public static final boolean VETO = true;
	public static final boolean NO_VETO = false;

	//Called just before the object is saved
	public boolean onSave(Session s) throws CallbackException;

	//Called when an entity is passed to Session.update().
	//This method is not called every time the object's
	//state is persisted during a flush.
	public boolean onUpdate(Session s) throws CallbackException;

	//Called just before an object is deleted
	public boolean onDelete(Session s) throws CallbackException;

	//Called just after an object is loaded
	public void onLoad(Session s, Serializable id);
}

需要注意的地方:

1,如果onSave()、onUpdate()、onDelete()方法返回VOTE(true)或者在以上方法中抛出了CallbackException异常,操作将会停止而不会调用之后的Session.save()、Session.update()、Session.delete()方法

2,并不是每次调用Session.update()方法之前都会调用onUpdate()方法

3,调用Session.get()方法会直接返回实体对象,故在调用该方法后会立即调用onload()方法,而调用Session.load()方法返回的是实体对象的代理,故在调用该方法后不会立即调用onload()方法

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值