How to automatically convert the List attribute of the entity class into Json into the library in SpringBoot

In the previous business development, the data received by a field was in Json format and needed to be stored in Json format:

image

This is stored in the database, here is actually a Json array.

[
  {
    "label": "result1",
    "name": "较好",
    "readonly": false
  },
  {
    "label": "result2",
    "name": "一般",
    "readonly": false
  },
  {
    "label": "result3",
    "name": "较差",
    "readonly": false
  },
  {
    "label": "result4",
    "name": "极差",
    "readonly": false
  }
]

If you want to access this data, what will you do? When saving, the front end will directly send you the data in Json format. When taking it out, you may convert the Json data into a List for other operations.

But in object-oriented thinking, each element in this Json array is an object, can we save it in the form of a List in the code layer, and then take it out in the form of a List, the middle Json conversion is automatically done by the program, No need to develop to manually transfer.

Of course there is a way to achieve it, let's see the effect:

image

We write this field in the entity class in Lis form, and add a @ColumnTypecomment on it. This annotation is used to realize automatic conversion between List and Json. Then it needs to be configured in the Mapper.xml file:

<result column="survey_conclusion_options" property="surveyConclusionOptions" typeHandler="com.xxx.SurveyConclusionTemplateTypeHandler" />

We add in this field typeHandler.

In this way, when we download the code to save the data, we add List instead of Json.

image

Check the database, it has been automatically converted to Json:

When we take it out, we only need to query directly, and we don't need to do other processing. What we return is a List.

image

Is it easy to access.

Now let's take a look at SurveyConclusionTemplateTypeHandlerthis conversion class in the field annotation .

image

Used here JsonTypeHandler, and specify the entity class.

Let's take a look JsonTypeHandler.

image

Mainly do Json processing. The complete code can be downloaded online.

Well, this article ends here, I hope it will be helpful to everyone.

Guess you like

Origin blog.csdn.net/wujialv/article/details/112215094