【问题标题】:how to store a collection of primitive type (String) into database如何将原始类型(字符串)的集合存储到数据库中
【发布时间】:2013-04-24 10:57:52
【问题描述】:

我正在尝试使用 ORMLite 将我的类映射到 SQLite 数据库,但我无法存储字符串集合,我遇到了这个错误:

java.lang.IllegalArgumentException: No fields have a DatabaseField annotation in
     class java.lang.String

这个错误是不言自明的,但是我应该如何存储字符串集合,我应该扩展 String 类并添加所需的注释来做到这一点? 在字段的注释中,我添加了 datatype.serializable 但这也行不通。 这是我遇到问题的班级:

@DatabaseTable(tableName = "parameters")

public class Parameters {

    // id is generated by the database and set on the object automagically
    @DatabaseField(generatedId = true)
    int id_parameters;

    @DatabaseField(canBeNull = true)
    @JsonProperty("id")
    private Integer id;

    @DatabaseField(canBeNull = false)
    @JsonProperty("account_id")
    private Integer account_id;

    @ForeignCollectionField
    @JsonProperty("languages")
    private Collection<String> languages;
    ...
}

相关领域是语言!

【问题讨论】:

    标签: android android-sqlite ormlite primitive-types foreign-collection


    【解决方案1】:

    是的,你不能只做一个字符串的集合。您需要创建一个包装类,其中包含一个 String 字段以及一个外部 Parameters 字段:

    public class Language {
        @DatabaseField(generatedId = true)
        int id;
        @DatabaseField
        String language;
        @DatabaseField(foreign = true)
        Parameters parameters;
    }
    

    这是来自 FM 的description of foreign collections。引用:

    请记住,当您有一个 ForeignCollection 字段时,集合中的类(在此示例中为 Order)必须具有用于具有该集合的类(在此示例中为 Account)的外部字段。如果 Account 有一个国外的 Orders 集合,那么 Order 必须有一个 Account foreign 字段。它是必需的,以便 ORMLite 可以找到与特定帐户匹配的订单。

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多