Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting a Collection class with ORMLite in android

I have two classes setup like the following. I am confused as to when I need to annotate something as an foreign collection and when I do not. This may also sound silly, but nowhere in the ORMLite documentation does it say whether or not a non-foreign collection is allowed. What if I have a List of ints which get autoboxed into Integers? can I just persist this using a standard @DatabaseField above the Collection? A foreign collection, according to ORMLite, must also have back reference for it to work (a reference to the parent, given a one to many realtionship). For the example below, I am assuming you should annotate myBList as a foreign collection as well as making myA a foreign object, but how could you handle myStringList?

I Have seen sample code here but it doesn't answer my questions: http://ormlite.com/docs/examples

public class A {

    private Set<B> myBList = new HashSet<B>();
    private List<String> myStringList = new ArrayList<String>();
    private long id;    
    public A(){}

    public Set<B> getMyBList() {
        return myBList;
    }
    public void setMyBList(Set<B> myBList) {
        this.myBList = myBList;
    }
    public List<String> getMyStringList() {
        return myStringList;
    }
    public void setMyStringList(List<String> myStringList) {
        this.myStringList = myStringList;
    }
    public void setId(long id){
        this.id = id;
    }

    public long getId(){
        return id;
    }
}

public class B {
    private int myInt;
    private String myString;
    private A myA;
    private long id;

    public B(){}

    public A getMyA(){
         return myA;
    }
    public A setMyA(A a){
        myA = a;
    }

    public int getMyInt() {
        return myInt;
    }
    public void setMyInt(int myInt) {
        this.myInt = myInt;
    }
    public String getMyString() {
        return myString;
    }
    public void setMyString(String myString) {
        this.myString = myString;
    }

    public void setId(long id){
        this.id = id;
    }

    public long getId(){
        return id;
    }
}
like image 448
Ryan Avatar asked Jun 07 '11 22:06

Ryan


1 Answers

@Robert is correct. When hibernate persists a collection (or even an array), it does so with hidden extra tables with foreign ids -- in other words hidden foreign collections. ORMLite tries to adhere to the KISS principle and so has you define the foreign collections "by hand" instead.

I've added more details about storing collections.

http://ormlite.com/docs/foreign-collection


This means that you cannot persist an Integer type because there is no foreign-id. Also, your code can define a foreign collection Collection<Order> or ForeignCollection<Order>. Either one will be set with a ForeignCollection. ORMLite does not support lists or other collection types.

like image 196
Gray Avatar answered Sep 22 '22 00:09

Gray