简体   繁体   中英

How value-based classes should be used in Hibernate entity classes

I have a Hibernate Entity class which implements Serializable interface with a LocalDate (a value-based class) field.

According to JPA spec

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

In my case I'm not going to use the objects in a different JVM so serializing and sending across a network is not needed. On the other hand, using a caching system justifies the need to implement serializable interface.

We have a SonarQube on this project. One of the rules pertaining to my case is as below which I'm quoting from a SonarQube rules.

A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class, whether directly via reference equality or indirectly via an appeal to synchronization, identity hashing, serialization...

Now, suppose I start to use a caching mechanism which is disk-based then based on the above rule and the very fact that in my Entity which is Serializable and the usage of a value-based field which cannot be turned to transient,

whats the best course of action? What is the proper way to use a value-based field in a Serializable Hibernate entity?

The note basically says that you should not try to base any of your logic based on the identity of a LocalDate (ie synchronize on a LocalDate, trying to distinguish two equal LocalDate with == or != , use them as keys of an IdentityMap, etc.).

That doesn't mean you can't serialize a class that contains a LocalDate. LocalDate implements Serializable, so that doesn't cause any problem.

My guess is that what the author meant to say regarding serialization is that you shouldn't make the assumption that serializing and then deserializing a LocalDate will give you a LocalDate with a different identity, as you can safely assume with traditional classes.

In short, treat a LocalDate as if it had no identity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM