Should @Transient property be used in equals/hashCode/toString?

后端 未结 3 1857
眼角桃花
眼角桃花 2021-02-06 03:08

I have JPA entities where some properties are annotated with @Transient.

Should I use these properties in equals/hashCode/toString methods?

3条回答
  •  醉梦人生
    2021-02-06 03:57

    The two typical usages of @Transient and transient that I'm aware of, are to use them either for stuff that can't be serialized/persisted (e.g. a remote resource handle) or computed properties which can be reconstructed from others.

    For computed data, it makes no sense to use them in the equality relationship (equals/hashCode), because it would be redundant. The value is computed out of other value which are already used in the equality. It can however still makes sense to print them in toString (e.g. a base price and a ratio are used to compute the actual price).

    For not serializable/persitable data, it depends. I can imagine a handle to a resource that is not serializable, but you can still compare the resource name that the handle represent. Same for toString, maybe printing the handle resource name is useful.

    This was my 2 cent, but if you explain your particular usage of @Transient, someone can maybe give a better advice.

提交回复
热议问题