定义 JSON 对应模型
示例代码
@Datapublic static class MobilePhone { private String iddCode; private String phoneNumber; public MobilePhone(String iddCode, String phoneNumber) { this.iddCode = iddCode; this.phoneNumber = phoneNumber; }}
定义模型与 JSON 转换
示例代码
package com.anydong.example.springboot.domain.converter;import com.alibaba.fastjson.JSON;import com.anydong.example.springboot.domain.UserDO;import javax.persistence.AttributeConverter;import javax.persistence.Converter;/** * @author where */@Converter(autoApply = true)public class MobilePhoneConverter implements AttributeConverter<UserDO.MobilePhone, String> { @Override public String convertToDatabaseColumn(UserDO.MobilePhone mobilePhone) { return JSON.toJSONString(mobilePhone); } @Override public UserDO.MobilePhone convertToEntityAttribute(String s) { return JSON.parseObject(s, UserDO.MobilePhone.class); }}
定义 JSON 类型字段
import javax.persistence.*;@Convert(converter = MobilePhoneConverter.class)@Column(columnDefinition = "JSON NULL")private MobilePhone phone;