6

We develop very usual spring MVC application
We have:
Controller layer (@RestComtroller + @GetMapping and @PostMapping)
Service layer(@Service)
Repository layer (CrudRepository from spring-data-jpa)

We use DTOs for communication between FE and BE.

Today my colleague asked me to mark all the DTOs as implements Serializable and add serialVersionUID field. I asked about reasons but he said that it is a "best practices". I am really confused about it. Serializable related to java serialization but we use JSON for BE and FE communication.

Could you clarify that question? So Should I mark spring mvc DTO with Serializable?

Andrew Tobilko
  • 46,063
  • 13
  • 87
  • 137
gstackoverflow
  • 34,819
  • 98
  • 304
  • 641

2 Answers2

3

No, you shouldn't.

Serialization implies that one side saves an object's state to a sequence of bytes while the other side rebuilds those bytes into a live object at some future time.

It means you should utilize Java Serialization API on the back-end side, pass the result over the network, and find a way how the received bytes can be helpful on the front-end side. The format of a serialized Java object is Java-specific and wasn't designed to be agnostic, so you will probably not find a reasonable (and short) way.

And you shouldn't (since you are communicating with the client via JSON).

Andrew Tobilko
  • 46,063
  • 13
  • 87
  • 137
1

The implementation of java.io.Serializable is simply required for transfering data via IIOP or JRMP (RMI) between JVM-instances. In case of a pure web application the domain objects are sometimes stored in HTTPSession for caching purposes. A http-session can be serialized or clustered. In both cases all the content have to be Serializable.

In most cases, there is no reason do make DTO Serializable, but I would like to extend my answer by adding this idea that in a more pragmatic architectures, the domain objects could also be exposed directly to the presentation layer. So instead of copying the data from domain objects into DTOs, which violates DRY Principal, you could just pass the detached JPA-entities as value holders to the web application. In this case it is better to implement java.io.Serializable.

To be more specific regarding your question,you should consider the following two facts when you want to decide whether you need to implement Serializable or not: