GreenDao按列名设置实体属性

时间:2017-10-19 09:46:32

标签: android greendao

我有一个包含500个属性的实体,每个属性都有人类可重新命名的名称,例如' serialNumber',但它的column_name是' E_A_XNF'。

现在我有一个表单,它为我提供了一个以列名作为键的Map。

我怎么能和GreenDao一样做:

String columnName = 'E_A_XNF';
String serialNumber = myMap.get(columnName);
entity.setByColumnName(columnName, serialNumber);

显然在实际程序中,我将循环遍历地图中的每个条目。

感谢。

编辑:

我有这个实体:

@Entity(nameInDb = "T_REF_CHAMP", generateConstructors = false,
        indexes = {@Index(value = "id", unique = true)})
public class ChampEntity {

    @Property(nameInDb = "ID_DAO")
    @Id
    private Long idDAO;

    @Property(nameInDb = "ID_CHAM")
    @NotNull
    private String id;

    @Property(nameInDb = "TAILLE_MAX_CHAM")
    private String tailleMaximum;

    @Property(nameInDb = "TYPE_CODE_CHAM")
    private String typeCode;

    @Property(nameInDb = "VAL_DEFAUT_CHAM")
    private String defaultValue;

    //more than 500 other property
    //more than 500 other property
    //more than 500 other property
    //more than 500 other property
    //more than 500 other property
    //more than 500 other property
    //more than 500 other property

    //getter setter

    }

然后我有了这个:

Map<String, String> dataToStore = new Hashmap<>();
dataToStore.put(ID_CHAM, "qzdqzddqzd");
dataToStore.put(TAILLE_MAX_CHAM, "122");
dataToStore.put(TYPE_CODE_CHAM, "lolola");
dataToStore.put(VAL_DEFAUT_CHAM, "ergot");
//more than 500 other values

如何使用此地图填充实体?因为实体只包含列实名。

1 个答案:

答案 0 :(得分:1)

你可以做的是使用反射。

//example class
public class TestEntity {
    @Property(nameInDb = "NAME")
    public String name;

    @Property(nameInDb = "SURNAME")
    public String surname;

    @Override
    public String toString() {
        return "TestEntity{" +
               "name='" + name + '\'' +
               ", surname='" + surname + '\'' +
               "}";
    }
}

//example map
Map<String, String> dataStore = new HashMap<>();
dataStore.put("NAME", "mat");
dataStore.put("SURNAME", "pag");

//use reflection to fill object
TestEntity te = new TestEntity();
Field[] fields = te.getClass().getFields();
for (Field field : fields) {
    //search the field for the GreenDao Property annotation
    Property propertyAnnot = field.getAnnotation(Property.class);
    if (propertyAnnot != null) {
        for (Map.Entry<String, String> pair : dataStore.entrySet()) {
            //match the map key and the nameInDb value
            if (pair.getKey().equals(propertyAnnot.nameInDb())) {
                try {
                    field.set(te, pair.getValue());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

//check the values of the filled object
te.toString();

显然,这不是性能优化,但您可以根据自己的逻辑自行完成。