Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are life-cycle listeners in Hibernate Serializable?

Tags:

java

hibernate

The Hibernate interfaces that you implement to provide event listeners, for example: org.hibernate.event.PostInsertEventListener; all extend Serializable.

However, it doesn't seem to explain anywhere why your listeners need to be serializable. We've been injecting DAOs with database connections into them for a while, and it hasn't failed yet, however I'm worried that there might be a case where Hibernate will pass the listener over a serialized link, and so lose the database connection.

So the question is: Why do hibernate event listeners have to be serializable?

like image 728
davidsheldon Avatar asked Nov 06 '22 20:11

davidsheldon


1 Answers

Although I'm not sure I understand your question correctly I don't know what the problem with a serializable event listener could be.

A event listener has to be implemented as if it was a singleton and they aren't supposed to hold any state in instance variables.

So serializing shouldn't be a problem.

A DAO can't be serialized (for obvious reasons).

If you really have an event listener with a reference to a DAO, mark the DAO instance variable as transient. When you use the DAO check for null and if null get the appropratie DAO from the DAOFactory.

like image 52
jitter Avatar answered Nov 11 '22 05:11

jitter