尝试转换枚举时出现ClassCastException

时间:2017-08-10 15:52:02

标签: java mongodb enums morphia

我在mongo中有一个名为文档的db集合 行与模块(教师模块/学生模块)相关:

document_id, document_type,          module 
0001         STUDENT_CARD,          STUDENTS
0002         DRIVER_LIC_CARD,          STUDENTS
0004         CAFETERIA_CARD,          TEACHERS
0005         DRIVER_LIC_CARD,          TEACHERS
0006         TEACHERS_AUTH_CARD,          TEACHERS

document_types被翻译成Java中的enum document.java记录包含字段:

private DocumentTypeEnum documentType;

这是DocumentTypeEnum结构:

public interface DocumentType{} // empty, just a tag
public enum  StudentDocumentTypeEnum  implements    DocumentType{...}
public enum  TeacherDocumentTypeEnum  implements    DocumentType{...}

当我使用morphia转换DBObject时,我得到了:

java.lang.ClassCastException: java.lang.String cannot be cast to     com.mongodb.DBObject
at org.mongodb.morphia.mapping.EmbeddedMapper.fromDBObject(EmbeddedMapper.java:65)
at org.mongodb.morphia.mapping.Mapper.readMappedField(Mapper.java:850)
at org.mongodb.morphia.mapping.Mapper.fromDb(Mapper.java:282)

所以我可以使用TypeConverter for morphia,有没有办法在转换时读取当前行信息?

    package com.xerox.infrastructure.config;

    import org.mongodb.morphia.converters.SimpleValueConverter;
    import org.mongodb.morphia.converters.TypeConverter;
    import org.mongodb.morphia.mapping.MappedField;

    import com.xerox.enums.DocumentTypeEnum;
    import com.xerox.enums.StudentDocumentTypeEnum;
    import com.xerox.enums.TeacherDocumentTypeEnum;

    public class EnumConverter extends TypeConverter implements SimpleValueConverter {

        @Override
        @SuppressWarnings("unchecked")
        public Object decode(final Class targetClass, final Object fromDBObject, final MappedField optionalExtraInfo) {
            if (fromDBObject == null) {
                return null;
            }

            //Pseudo code 
            If the current row -> module  is  Teacher
                    then return TeacherDocumentTypeEnum.valueOf(fromDBObject.toString());

            //Pseudo code       
            else If the current row -> module  is from module Student
                    then return StudentDocumentTypeEnum.valueOf(fromDBObject.toString());

           return  TeacherDocumentTypeEnum.valueOf(fromDBObject.toString());
        }

        @Override
        public Object encode(final Object value, final MappedField optionalExtraInfo) {
            if (value == null) {
                return null;
            }

            return getName((Enum) value);
        }

        @Override
        protected boolean isSupported(final Class c, final MappedField optionalExtraInfo) {
            return DocumentTypeEnum.class.equals(c) || 
                    TeacherDocumentTypeEnum.class.equals(c) || 
                            StudentDocumentTypeEnum.class.equals(c)         ;
        }

        private <T extends Enum> String getName(final T value) {
            return value.name();
        }
    }

0 个答案:

没有答案