javajpaenumsdeserializationpostgres-10

How to serialize and deserialize multi argument enum in Java using JPA 2.1 or lower (Postgres)



    public enum CameraType {
    
    CAMERA(false, false, "External lens ", ""),
    
    
    CameraType{
                boolean collector,
                boolean hidden,
                String description
            ) {
            this.collector = collector;
            this.granular = hidden;
            this.description = description;
            } // end ctor
           
           public void setHide(boolean hidden) {
               this.hide = hidden;
           }
    
    } // end enum

I have few Instance of CameraType.

I have a setter for "hidden" property which on certain condition is set to true or false.

Now I serialize CameraType with few other fields inside SecurityEntity.

```
@Entity
@Table
public class Security {

 Few more fields...

@Enumerated(EnumType.STRING)
    @Column(nullable = false)
private CameraType cameraType

And other fields...
}
```

When I deserialize the value of "hidden" field is always false. If I understand correctly, during deserialization ctor is called and default is assigned.

Is there a way I can retain the value of "hidden" field(true or false) after deserialization per instance of CameraType.

I am using Postgres DB 10.

enter code here

Please Please help. I am out of clues.


Solution

  • By definition, enums are immutable elements of a fixed set. Because of this, to represent an enum value you just need its name. That's exactly what JPA does during serialization/deserialization.

    You are trying to violate the rules. While Java allows you to treat enums almost as plain objects, JPA treats them according to what they are supposed to be. That's why your code is not working.

    You can either: