7

greenDAOを使い始めたばかりです。Enum プロパティを追加するにはどうすればよいですか?

私が考えたこと:エンティティの addIndex プロパティを使用します。

private static void main() {

    // TODO Auto-generated method stub
    static Schema blah;
    Entity unicorn = blah.addEntity("Weather");
    unicorn.addIdProperty();
    unicorn.addIntProperty("currentAirTemp");
    unicorn.addIndex("shirtSize");
}

これは正しい方法ですか?

目的:セットからの shirtSize への参照が必要です: {XS、S、M、L、XL、XXL}

4

3 に答える 3

22

GreenDAO 3 を使用すると、@convert注釈を使用するオプションが追加されましたPropertyConverter

@Entity
public class User {
    @Id
    private Long id;

    @Convert(converter = RoleConverter.class, columnType = String.class)
    private Role role;

    enum Role {
        DEFAULT, AUTHOR, ADMIN
    }

    static class RoleConverter implements PropertyConverter<Role, String> {
        @Override
        public Role convertToEntityProperty(String databaseValue) {
            return Role.valueOf(databaseValue);
        }

        @Override
        public String convertToDatabaseValue(Role entityProperty) {
            return entityProperty.name();
        }
    }
}

詳しくはhttp://greenrobot.org/objectbox/documentation/custom-types/をご覧ください。

于 2016-09-15T05:55:53.553 に答える
2

私の知る限り、列挙型は不安定な性質のため、greenDAO ではサポートされていません。また、列挙型要素の値は変更される可能性があるため、データベース ロジックに追加するエラーが発生しやすいコンポーネントでもあります。

これを回避する 1 つのオプションは、次のように Int プロパティをデータベースに追加し、Enum 序数値をそのフィールドにマップすることです。

// add the int property to the entity
unicorn.addIntProperty("shirtSize");

// create the enum with static values
public enum ShirtSize {
    XS(1), S(2), M(3), L(4), XL(5), XXL(6);

    private final int value;

    private ShirtSize(int value) {
        this.value = value;
    }

    public int value() {
        return value;
    }
}

// set the ordinal value of the enum
weather.setShirtSize(ShirtSize.XL.value());
于 2014-09-16T15:57:39.153 に答える