有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在寻找一种方法,用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;
}

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


共 (1) 个答案

  1. # 1 楼答案

    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中存在的方法才可用