Search code examples
androidmany-to-manydaoormlite

ORMLite many to many relation


In order to make a many to many relation between these two class with ORMLite :

@DatabaseTable(tableName = "test1")
public class Test1 {
    @ForeignCollectionField
    private ForeignCollection<Test2> test2Collection;
}

@DatabaseTable(tableName = "test2")
public class Test2 {
    @ForeignCollectionField
    private ForeignCollection<Test1> test1Collection;
}

I'm facing to the problem that ORMLite at the tables creation, don't know about the Foreign Keys between this class..

In order to make this relation do I have to add a single ForeignDatabaseField on each class like this:

@DatabaseTable(tableName = "test1")
public class Test1 {
    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    private Test2 test2;
    @ForeignCollectionField
    private ForeignCollection<Test2> test2Collection;
}
@DatabaseTable(tableName = "test2")
public class Test2 {
    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    private Test1 test1;
    @ForeignCollectionField
    private ForeignCollection<Test1> test2Collection;
}

It seems to be a strange way?


Solution

  • In order to make this relation do I have to add a single ForeignDatabaseField on each class like that:

    With a many-to-many relationship, the best way to associate objects together is with a "join table". In your case, there would be a 3rd table named Test1Test2Join or something.

    @DatabaseTable(tableName = "test1test2join")
    public class Test1Test2Join {
        @DatabaseField(generatedId = true)
        private long id;
        @DatabaseField(foreign = true)
        private Test1 test1;
        @DatabaseField(foreign = true)
        private Test test2;
    }
    

    For more information, see the many-to-many example.