Why serialize entity classes in JPA

In previous development projects, I didn't care too much about serialization. I only knew how to use it, but I didn't know why. Share your experience after learning.

For serialization, we must first understand what serialization is. Serialization is the process of converting the properties of an object into a process that can be read and written. Normally, all fields of an entity object are serialized.

So why serialize?

Generally, the objects generated during the running of the program will disappear as the program stops, so how do we store these objects? Just like the fields of the entity class, you need to store the fields in the corresponding database in the project, so serialization can help you solve the storage problem. The reason for serialization is because sometimes objects need to be transmitted on the network. This kind of serialization processing is required during transmission. The serialized objects are taken out from the server database, and then transmitted to the client through the network, and then the client sends them to the client. The serialized object is read into memory, and the corresponding processing is performed. Simply put, serialization is to convert objects into bytecodes, and deserialization is to reverse the serialization process.

How to use serialization?

@Entity
public class xxxx extends BaseEntity implements Serializable {

	private static final long serialVersionUID = 1L;

Generally, for entity classes, we will choose to inherit the Serializable interface, so that a SerialVersionUID will be generated by default, and the version consistency will be verified by judging the serialVersionUID of the entity class. When deserializing, the JVM will compare the serialVersionUID in the incoming byte stream with the serialVersionUID of the corresponding local entity class. If they are the same, they are considered consistent and can be deserialized. Otherwise, an InvalidCastException exception will occur .

Of course, serialVersionUID=1L is generated by default, and we can also customize this. Because the serialVersionUID generated by default is very sensitive to the details of the class, it is best to customize one according to specific needs to avoid program errors.

Of course, we can use some fields that do not need to be serialized

@JSONField(serialize = false)

Guess you like

Origin blog.csdn.net/weixin_51220967/article/details/123993552