将对象列表保存到 ORMLite 数据库

Save a list of objects to ORMLite database

我正在寻找一种使用 ORMLite 将对象列表保存到数据库的方法,并阅读了这个问题:Best way to store several ArrayLists in ORMLite for ApplicationSettings

接受的答案对我来说很有意义:

public class YourClass {
    @GeneratedId
    private int id;

    @ForeignCollectionField
    private Collection<MyString> bunchOfStrings = new ArrayList<MyString>();
}

public class MyString{
     @DatabaseField(canBeNull = true, foreign = true)
     private YourClass yourClass;

     @DatabaseField
     private String text;
}

我唯一不明白的是这一行private Collection<MyString> bunchOfStrings = new ArrayList<MyString>()。为什么我们将 ForeignCollectionField 保存为 Collection<MyString> 而不是 ArrayList<MyString>?使用上面的 bunchOfStrings 对象时,我们是否总是需要将其转换为 ArrayList<MyString>

Why do we save the ForeignCollectionField as Collection instead of as ArrayList?

这是设计考虑,摘自 doc

The field type of orders must be either ForeignCollection<T> or Collection<T> – no other
collections are supported because they are much heavier with many methods to support

When working with the bunchOfStrings object above, do we always need to cast it to ArrayList

您不必初始化该字段,Ormlite 会这样做。因此,只有 Collection 或 ForeignCollection

中存在的可用方法