定义 JSON 对应模型

示例代码

  1. @Data
  2. public static class MobilePhone {
  3. private String iddCode;
  4. private String phoneNumber;
  5. public MobilePhone(String iddCode, String phoneNumber) {
  6. this.iddCode = iddCode;
  7. this.phoneNumber = phoneNumber;
  8. }
  9. }

定义模型与 JSON 转换

示例代码

  1. package com.anydong.example.springboot.domain.converter;
  2. import com.alibaba.fastjson.JSON;
  3. import com.anydong.example.springboot.domain.UserDO;
  4. import javax.persistence.AttributeConverter;
  5. import javax.persistence.Converter;
  6. /**
  7. * @author where
  8. */
  9. @Converter(autoApply = true)
  10. public class MobilePhoneConverter implements AttributeConverter<UserDO.MobilePhone, String> {
  11. @Override
  12. public String convertToDatabaseColumn(UserDO.MobilePhone mobilePhone) {
  13. return JSON.toJSONString(mobilePhone);
  14. }
  15. @Override
  16. public UserDO.MobilePhone convertToEntityAttribute(String s) {
  17. return JSON.parseObject(s, UserDO.MobilePhone.class);
  18. }
  19. }

定义 JSON 类型字段

  1. import javax.persistence.*;
  2. @Convert(converter = MobilePhoneConverter.class)
  3. @Column(columnDefinition = "JSON NULL")
  4. private MobilePhone phone;