Rauter Rauter - 5 months ago 19
Android Question

How does ORMLite store ForeignCollections in the database?

I have two classes, User and Artwork. User can have a collection of Artworks. Everything works as expected, I can store and retrieve the objects from the db, but I don,t understand how they collection is persisted.

public class User {

@DatabaseField(allowGeneratedIdInsert = true, generatedId = true, unique = true)
Long id;

@DatabaseField
String name;

@DatabaseField(columnName = "artwork_id", foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
Artwork masterPiece;

@ForeignCollectionField(eager = true)
Collection<Artwork> artworks;
}

public class Artwork {

@DatabaseField(allowGeneratedIdInsert = true, generatedId = true, unique = true)
Long id;

@DatabaseField
String name;

@DatabaseField
String file;

@DatabaseField(columnName = "user_id", foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
User owner;
}


I create some artworks, add them to the collection and set the collection in the a User. When checking the .db (.schema) I get this:

CREATE TABLE android_metadata (locale TEXT);
CREATE TABLE `user` (`id` INTEGER PRIMARY KEY AUTOINCREMENT , `name` VARCHAR , `artwork_id` BIGINT );
CREATE TABLE `artwork` (`id` INTEGER PRIMARY KEY AUTOINCREMENT , `name` VARCHAR , `file` VARCHAR , `user_id` BIGINT );


Objects are being correctly inserted and querying for them works like charm. What I really don't understand is why I there is no field for the collection.

Answer

User and Artwork entities has one-to-many relationship. In relational databases this is modeled as Artwork having a column which references User (user_id, in this case). To get collection of Artwork associated with User (id), ormlite executes query which roughly looks like:

select * from Artwork where user_id = id

Comments