UserProfileModel具有两个嵌入式模型。我在这里简明扼要地给出:
@Document(collection = "USER_PROFILE")
public class UserProfileModel extends BaseModel<UserModel> {
public static final String FIELD_USER_ID = "userId";
public static final String FIELD_BASIC_INFO = "basicInfo";
public static final String FIELD_CONTACT_INFO = "contactInfo";
private String userId;
private BasicInfo basicInfo;
private ContactInfo contactInfo;
}
public class BasicInfo {
private String gender;
private LocalDate birthDate;
private String[] langs;
private String religiousView;
private String politicalView;
}
public class ContactInfo {
private String[] mobilePhones;
private Address address;
private SocialLink[] socialLinks;
private String[] websites;
private String[] emails;
}
UserProfileModel的写转换器类:
@Component
@WritingConverter
public class UserProfileModelConverter implements Converter<UserProfileModel, Document> {
@Override
public Document convert(UserProfileModel s) {
Document doc = new Document();
if (null != s.getUserId())
doc.put(UserProfileModel.FIELD_USER_ID, s.getUserId());
if (null != s.getBasicInfo())
doc.put(UserProfileModel.FIELD_BASIC_INFO, s.getBasicInfo());
if (null != s.getContactInfo())
doc.put(UserProfileModel.FIELD_CONTACT_INFO, s.getContactInfo());
}
}
试图像这样保存UserProfileModel的对象:
@Autowired
private UserProfileRepository repo;
UserProfileModel profileModel = generateUserProfileModel();
repo.save(profileModel);
Exception:
org.bson.codecs.configuration.CodecConfigurationException: An exception occurred when encoding using the AutomaticPojoCodec.
Encoding a BasicInfo: 'BasicInfo(gender=Male, birthDate=2020-05-05, langs=[Lang 1, Lang 2], religiousView=Islam (Sunni), politicalView=N/A)' failed with the following exception:
Failed to encode 'BasicInfo'. Encoding 'langs' errored with: Can't find a codec for class [Ljava.lang.String;.
A custom Codec or PojoCodec may need to be explicitly configured and registered to handle this type.
at org.bson.codecs.pojo.AutomaticPojoCodec.encode(AutomaticPojoCodec.java:53)
at org.bson.codecs.EncoderContext.encodeWithChildContext(EncoderContext.java:91)
at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:185)
at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:199)
at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:141)
at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:45)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:29)
如果我不通过在Mongo Config中添加将UserProfileModel
用作转换器,则不会出现此异常,并且一切正常。
但是出于某种原因,我试图使用Converter类。
那么转换器类是否有问题或需要修改?
已在此问题上提出了一张吉拉车票here。
找不到类[Ljava.lang.String;]的编解码器
以及他们的回复
Document类当前仅支持列表,不支持本机Java 数组,因此只需替换为:
列表代码= Arrays.asList(“ 1112233”,“ 2223344”);
因此,不支持字符串数组。在模型中使用
List<String>
代替String[]
。