views:

57

answers:

3

I have a PersistenceCapable class

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class MyClass
{
 @PrimaryKey
 @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
 private Long id;
         ..........
         ..........
}

In my servlet, I need to store object of this class in session

............
MyClass u = new MyClass();
......
......
HttpSession session = req.getSession(true);
session.setAttribute("SV", u);
........

I am getting java.lang.RuntimeException: java.io.NotSerializableException:

What is this?

+3  A: 

Sessions can be temporarily stored on disk or migrated to another application server. In order to make sure that objects in the session can be handled in those situations they need to be serailisable. You can flag this by implementing the Serializable interface:

import java.io.Serializable;

public class MyClass implements Serializable {
}
rsp
Can you show me where i can write the flag to make it serializable?
Manjoor
@Manjoor - `public class MyClass implements Serializable`
Petar Minchev
A: 

I guess putting a bunch of annotations in your class does not make it implement the Serializable interface. Why should it? Do public class MyClass implements Serializable { ...

David Soroko
it could, if there was an annotation processor present that modified the source code. But I guess there isn't
seanizer
In OP's example we have:`MyClass u = new MyClass();......HttpSession session = req.getSession(true);` which does not leave much room for annotation processor
David Soroko
+1  A: 

rsp is right: Serializable is the correct answer, but implementing Serializable is only the first step. E.g. you need to also make all fields either Serializable or transient.

Read one of the many tutorials about Java Serialization, or best of all: buy Effective Java by Joshua Bloch and read all of it, including the 4 chapters about Serialization.

seanizer