What is the use of implementing Serializable
interface in hibernate entity class?
That interface continue nothing in that.

- 3,582
- 2
- 30
- 41

- 57
- 1
- 3
- 8
2 Answers
It's Marker Interface and just like an normal interface.
The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata.
In Serializable
case java
public interface Serializable{
}
and some class
public class someObje implements Serializable{
}
And somewhere else Runtime
realizes objects like
if(someObje instnaceOf Serializable){
//Hey this object can serialize you know. Grant security permission.
}
Coming to your question, by definition
Serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
Now without Serialization ,how hibernate entities move in your application (Client <=> Server <=> Database)
?
And also to detect the type. For ex in hibernate look at the method signature of Seesion#get() method
Object get(Class clazz,
**Serializable** id)
throws HibernateException
Note:This theory applies not only for hibernate entities where ever Object
needs to be serialize.

- 120,458
- 37
- 198
- 307
-
why would hibernate entities inned to be `Serializable ` move your application ? – Santosh Dec 13 '13 at 07:54
-
For example, Client <=> Server, since they are the domain object ?? And a little edit on my post too. – Suresh Atta Dec 13 '13 at 07:57
-
I understand that. My query was specific to hibernate related operations. – Santosh Dec 13 '13 at 08:04
-
Consider a small example : Without serialization, how can Domain objects `Id` `ex :(setId(long))` Is saving as a primary key in your database ?? If your object is not Serializable, java won't give that information to underlying database. – Suresh Atta Dec 13 '13 at 08:09
-
Well, that's true [about the keys](http://stackoverflow.com/questions/9271835/why-composite-id-class-must-implement-serializable) (primary, composite) but not the entities in general. – Santosh Dec 13 '13 at 08:37
-
@Suresh Hibernate in turn fires SQL queries. `setId(long);` doesn't mean that the object is serialized and stored somewhere. It will eventually lead to an `update` statement getting fired, thereby storing the Id value in DB table. – Aman Arora May 26 '14 at 06:50
- Not sure why in Hibernate entity classes need to implement
Serializable
interface. ASerializable
POJO is the one which can be written to the disc or transmitted over the wire. - If your Hibernate entities or POJOs are involved in any of these then only you need to implement
Serializable
interface.
EDIT:
- Just realized that the keys (primary, composite) needs to be Serializable
as they are referred by persistent Session
. (Reference)

- 17,667
- 4
- 54
- 79