views:

563

answers:

5

The question is in the title. Below I just described some of my thoughts and findings.

When I had very simple domain model (3 tables without any relations) all my entities did NOT implement Serializable.

But when domain model became more complex I got RuntimeException which said that one of my entities didn't implement Serializable.

I use Hibernate as a JPA implementation.

I wonder:

  1. Is it vendor-specific requirement/behavior?
  2. What happens with my serializable entities? Should they be serializable for storing or for transferring?
  3. At which moment it becomes necessary to make my entity serializable?
+1  A: 

You need your entities to be Serializable if you need to transfer them over-the-wire (serialize them to some other representation), store them in http session (which is in turn serialized to hard disk by the servlet container), etc.

Just for the sake of persistence, Serializable is not needed, at least with Hibernate. But it is a best practice to make them Serializable.

Bozho
I don't know, maybe my entities are being transferred implicitly somewhere. I use hibernate+spring+jsf and Tomcat. Where in this chain transferring can take place?
Roman
+1  A: 

Classes must implement Serializable if you want to serialize them. This is not directly related to JPA and the JPA specification does not require that entities are serializable. If Hibernate really complains about this, I suppose it is a Hibernate bug, but I suppose that you directly or indirectly are doing something else with the entities, which require them to be serializable.

jarnbjo
+1  A: 

This usually happens if you mix HQL and native SQL queries. In HQL, Hibernate maps the types you pass in to whatever the DB understands. When you run native SQL, then you must do the mapping yourself. If you don't, then the default mapping is to serialize the parameter and send it to the database (in the hope that it does understand it).

Aaron Digulla
+4  A: 

According to JPA Spec:

"If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface."

"JSR 220: Enterprise JavaBeansTM,Version 3.0 Java Persistence API Version 3.0, Final Release May 2, 2006"

Conor
(+1) looking at the spec is always fruitful
Bozho
A: 

In our application, I noticed the same as none of the entities implements Serializable. I started to wonder why? We are using Hibernate for mapping and EJB 3/JPA for persistence. I do not think it has anything to do with implementing Serializable.

According to JPA specification as indicated above, Serializable is only required for Remote Interface. We are using Local Interface so I guess it is implicit and not required.

Smith James