Elia
Elia

Reputation: 1443

Foreign collection field not present in db

I have two simple class like this:

@DatabaseTable(tableName = "movements")
public class Movement {

    @DatabaseField(generatedId = true)
    int id;

    @DatabaseField
    double amount;

    @DatabaseField(foreign = true)
    Category category;

    @ForeignCollectionField(eager = true)
    Collection<Tag> tags;

    //Other stuff
}

And the second:

@DatabaseTable(tableName = "tag")
public class Tag {

    @DatabaseField(generatedId = true)
    int id;

    @DatabaseField(foreign = true)
    Movement movement;

    @DatabaseField
    String name;

    //Other stuff
}

What I expect by the following two commands:

TableUtils.createTable(dbConnection, Tag.class);
TableUtils.createTable(dbConnection, Movement.class);

is the creation of two table inside the db with right references once to the other. Instean seems that the ForeignCollection inside the 'Movement' class was ignored. This is may debug infos:

[INFO] TableUtils creating table 'tag'
[INFO] TableUtils executed create table statement changed 0 rows: CREATE TABLE `tag` (`id` INTEGER AUTO_INCREMENT , `movement_id` INTEGER , `name` VARCHAR(255) , PRIMARY KEY (`id`) ) 
[INFO] TableUtils creating table 'movements'
[INFO] TableUtils executed create table statement changed 0 rows: CREATE TABLE `movements` (`id` INTEGER AUTO_INCREMENT , `amount` DOUBLE PRECISION , `category_id` INTEGER , PRIMARY KEY (`id`)

I can't see my mistake!

Upvotes: 1

Views: 142

Answers (1)

Gray
Gray

Reputation: 116888

Instean seems that the ForeignCollection inside the 'Movement' class was ignored.

Yeah it is a bit confusing but there is no mistake. There is nothing in the movements table that refers to tags in the database.

The way foreign-collections work in ORMLite (like hibernate and other ORMs) is that a tag has a reference to the associated movement_id, but not the other way around. A movement can't have some sort of list of tag ids by definition. That's why ORMLite uses another query to fill out the tags collection. It returns your movement and then it looks up the id from the movement to find the tags that have the same in the movement_id field.

Upvotes: 1

Related Questions