Why implement Serializable on models? - java

I noticed in Spring-boot a lot of people create models/entities and implement the Serialiazable interface.
public class ModelBase implements Serializable
I understand what it means to serialize data/classes as it enables you to save the state of a class (if I'm not wrong, to a file for instance).
But I believe this should be done only when necessary, but either way it seems people just tend to implement the interface.
Is there a different reason?

When your models or entities are meant to travel across several JVM's then you might want to consider implementing Serializable interface. You should do this with caution. You should also provide a a valid UUID for the class to be used during Serialization and vice versa.
Sample is
private static final long serialVersionUID = 9178661439383356177L;
And
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.
Also
When using serializable values it is possible to remove this redundancy by changing the entity class in two ways:
Make the entity class serializable, so it can be used in place of the value class.
Make the key fields transient, so they are not redundantly stored in the record.
https://docs.oracle.com/cd/E17277_02/html/collections/tutorial/SerializableEntity.html

Related

Wondering if I need to implements serializable interface or not?

I am new to MyBatis, I saw some code which define model as
public class model implement serializable {
****
}
but some codes simple define without serializable interface.
I am wondering which is better? Serializable is an empty interface actually.
You need to define the Serializable interface if you plan to serialize instances of your class. It's that simple.
Many do it out of routine, but the entire point of Serializable is that some classes can NOT be serialized correctly. By making you implement this interface, you make the conscious decision that your class, in fact, can be serialized.
Mybatis don't require serialization. It dynamically calls constructor after executing query and create bean objects.
So answer is no you don't need to implement Serializable interface.
Serializable is a marker interface and has no method. It just tell jvm that you are intrested to serialize the type and rest will be done automatically.

Why to serialize model class

Many times I see a model class will implement Serializable, but is never serialized.
What is purpose here to implement Serializable?
If serialization is not used, what will I miss? Is there any effect in the way the code communicates?
public class Stock implements Serializable{
private int stockId;
private String stockCode;
private String stockName;
//Getter and setter
}
What is purpose here to implement Serializable?
Just a marker to indicate the possibility provided to clients of the class for serializing instances of them if they wish.
For example, if you instantiate Stock class and that you want to save Stock instances in a file, you can do it thanks to this marker. APIs (for example Jaxb or Java native serialization mechanism) rely generally on the implementation of this interface to serialize class.
If serialization is not used, what will I miss? Is there any effect in
the way the code communicates?
It's is not used, you have zero overhead or transformation in the communication of the instance since it is a marker interface. Only, when the serialization occurs, the communication of the instance changes.
Serializable is just a marker interface without overhead*.
If you want class A to implement serializable and class A contains field with type Stock, Stock should also implement serializable.
May be there will be no direct Stock class instance serializations. But it will be serialized via class A instance.
Also implementing is necessary if you want Stock instance to become an argument of
type foo(? extends Serializable param)

Implementing Serializable interface in hibernate entity class

What is the use of implementing Serializable interface in hibernate entity class?
That interface continue nothing in that.
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.
Not sure why in Hibernate entity classes need to implement Serializable interface. A Serializable 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)

RMI marshal and serialization

In java using RMI to marshal an object that you are returning from the remote class do you just need to implement Serializable on that object? I have a class node with variables inside that i want to be returned. Do i just implement serializable? If so what about the class that is receiving the object? does its class need to implement serializable too?
example:
public class node implements Serializable{
//variables
//variables
public node(//arguments to constructor here){
}
}
The class that is being serialized needs to implement Serializable. The sending and receiving classes don't. Not sure why you would think otherwise.
If you have a class whose instances you want to serialize using built-in Java serialization, not only must it implement Serializable, all its instance variables must also implement Serializable, or be primitives, or be marked transient (i.e. you tell the JVM that it's okay for them to not get serialized).
If your class can't conform to these constraints for some reason, you can implement custom serialization behavior yourself by implementing Externalizable - then you take responsibility for writing out your object's state and reading it back on the other end.
I'm not sure whether I understand your question correctly or not, but ... if the serializable class has other objects as member variables, then better make them serializable also, otherwise better declare as transient to skip. does this answer your question?
if code inspector program is handy, you can have answer for such question very quickly without posting it
for your tip, only the object you wan to persist or transfer needs to implements Serializable, so the object can be reconstructed as the class structure through serializing/unserializing

Java: What can and what can't be serialized?

If the Serializable interface is just a Marker-Interface that is used for passing some-sort of meta-data about classes in java - I'm a bit confused:
After reading the process of java's serialization algorithm (metadata bottom-to-top, then actual instance data top-to-bottom), I can't really understand what data cannot be processed through that algorithm.
In short and formal:
What data may cause the NotSerializableException?
How should I know that I am not supposed to add the implements Serializable clause for my class?
First of all, if you don't plan to ever serialize an instance of your class, there is no need to even think about serializing it. Only implement what you need, and don't try to make your class serializable just for the sake of it.
If your object has a reference (transitive or direct) to any non-serializable object, and this reference is not marked with the transient keyword, then your object won't be serializable.
Generally, it makes no sense to serialize objects that can't be reused when deserialized later or somewhere else. This could be because the state of the object is only meaningful here and now (if it has a reference to a running thread, for example), or because it uses some resource like a socket, a database connection, or something like that. A whole lot of objects don't represent data, and shouldn't be serializable.
When you are talking about NotSerializableException it is throw when you want to serialize an object, which has not been marked as Serializable - that's all, although when you extend non serializable class, and add Serializable interface it is perfectly fine.
There is no data that can't be serialized.
Anything your Serializable class has in it that is not Serializable will throw this exception. You can avoid it by using the transient keyword.
Common examples of things you can't serialize include Swing components and Threads. If you think about it it makes sense because you could never deserialize them and have it make sense.
All the primitive data types and the classes extend either Serializable directly,
class MyClass extends Serializable{
}
or indirectly,
class MyClass extends SomeClass{
}
SomeClass implements Serializable.
can be serialized. All the fields in a serializable class gets serialized except the fields which are marked transient. If a serializable class contains a field which is not serializable(not primitive and do not extend from serializable interface) then NotSerializableException will be thrown.
Answer to the second question : As #JB Nizet said. If you are going to write the instance of a class to some stream then and then only mark it as Serializable, otherwise never mark a class Serializable.
You need to handle the serialization of your own Objects.
Java will handle the primitive data types for you.
More info: http://www.tutorialspoint.com/java/java_serialization.htm
After reading the process of java's serialization algorithm (metadata bottom-to- top, then actual instance data top-to-bottom), I can't really understand what data cannot be processed through that algorithm.
The answer to this is certain system-level classes such as Thread, OutputStream and its subclasses which are not serializable. Explained very well on the oracle documents: http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html
Below is the abstract:
On the other hand, certain system-level classes such as Thread, OutputStream and its subclasses, and Socket are not serializable. Indeed, it would not make any sense if they were. For example, thread running in my JVM would be using my system's memory. Persisting it and trying to run it in your JVM would make no sense at all.
NotSerialisable exception is thrown when something in your serializable marked as serializable. One such case can be:
class Super{}
class Sub implements Serializable
{
Super super;
Here super is not mentioned as serializable so will throw NotSerializableException.
More practically, no object can be serialized (via Java's built-in
mechanism) unless its class implements the Serializable interface.
Being an instance of such a class is not a sufficient condition,
however: for an object to be successfully serialized, it must also be
true that all non-transient references it holds must be null or refer to
serializable objects. (Do note that that is a recursive condition.)
Primitive values, nulls, and transient variables aren't a problem.
Static variables do not belong to individual objects, so they don't
present a problem either.
Some common classes are reliably serialization-safe. Strings are
probably most notable here, but all the wrapper classes for primitive
types are also safe. Arrays of primitives are reliably serializable.
Arrays of reference types can be serialized if all their elements can be
serialized.
What data may cause the NotSerializableException?
In Java, we serialize object (the instance of a Java class which has already implemented the Serializable interface). So it's very clear that if a class has not implemented the Serializable interface, it cannot be serialized (then in that case NotSerializableException will be thrown).
The Serializable interface is merely a marker-interface, in a way we can say that it is just a stamp on a class and that just says to JVM that the class can be Serialized.
How should I know that I am not supposed to add the implements
Serializable clause for my class?
It all depends on your need.
If you want to store the Object in a database, you can
serialize it to a sequence of byte and can store it in the
database as persistent data.
You can serialize your Object to be used by other JVM working
on different machine.

Categories