shivang sarawagi wrote:I googled everywhere ideally I should use a long to persist the class property.
Well the class has a field which is the count of people following a movie. The entity is movie. User & Movie have a ManyToMany relationship. Every time a user follows a movie the count gets incremented & updated in the db therefore I've made it AtomicLong as the count is shared amongst multiple users; just like facebook likes for a post.If you think my design is incorrect please advice.
If I make the field as Long how do I share it amongst several threads? Or do I just write a concurrent strategy for the object access & update to & fro from the db & just simply use the long variable?
Entities are explicitly not meant to be shared among multiple threads. That's because multi-threaded transactions are not supported. At some point the entity would need to be persisted, but from which
thread and at what time?
I would make the field a long field with no (public) setter, making it virtually unchangeable. Then I would add a method to some bean that uses a JPQL query to update the count:
As a side note, JPA supports only a few types. Any type that does not match those will tried to be serialized to a byte[]. That's where you got the error from, because AtomicLong is not Serializable.
If you use JPA 2.1 you can use AttributeConverter, @Convert, @Converts and @Converter to define custom mappings to the supported types.
If I recall correctly, the supported types:
- primitives and primitive wrappers.
- BigInteger and BigDecimal
- enums.
-
String, char[] and CharSequence.
- byte[] and objects implementing Serializable
- Calendar, java.util.Date, java.sql.Date, java.sql.Time and java.sql.Timestamp (support for classes in java.time will come in JPA 2.2 or later).
- Collection, List, Set and Map (either as @ElementCollection, @ManyToMany or @OneToMany).
- other entities (either as @ManyToOne or @OneToOne).
- embeddables.