adalpari
adalpari

Reputation: 3121

ORMLite is not creating the foreign reference

I'm trying to persist two kind of objects. Family and Subfamily. One Family has one or more Subfamilies.

The problem that I have is that I can storage data, BUT foreign reference is always NULL.

These are the classes, which create the correct database structure:

Family.java

@DatabaseTable
public class Family {

    @DatabaseField(id = true)
    private Integer id;

    @DatabaseField
    private String name;

    @ForeignCollectionField(eager = true)
    private ForeignCollection<Subfamily> subfamilies;

    public Family() {}

    // public getters and setters
}

Subfamily.java

@DatabaseTable
public class Subfamily {
    @DatabaseField(id = true)
    private Integer id;

    @DatabaseField(foreign = true, foreignAutoRefresh = true)
    private Family family;

    @DatabaseField
    private String name;

    public Subfamily() {}

    public Subfamily(String name, Family family) {
        this.name = name;
        this.family = family;
    }

    // public getters and setters
}

Then I have separated Daos, for insert Family and Subfamily

public void insertFamily(Family family) {
    try {
        this.familyDao.create(family);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}


public void insertSubfamily(Subfamily subfamily) {
    try {
        this.subfamilyDao.create(subfamily);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Then when I create a Family and Subfamily like this, the foreign field looks always NULL. I Don't know what I'm doing wrong..

Family f1 = new Family("FAMILY ONE");
mFamilyDao.insertFamily(f1);
Subfamily s1 = new Subfamily("SUBFAMILY OF FAMILY ONE", f1);
mSubfamilyDao.insertSubfamily(s1);

Foreign null

Upvotes: 1

Views: 203

Answers (1)

Gray
Gray

Reputation: 116878

Then when I create a Family and Subfamily like this, the foreign field looks always NULL. I Don't know what I'm doing wrong..

Family f1 = new Family("FAMILY ONE");
familyDao.insertFamily(f1);
Subfamily s1 = new Subfamily("SUBFAMILY OF FAMILY ONE", f1);
subfamilyDao.insertSubfamily(s1);

Ok. This code on the surface looks fine so the following list is more things to try and debugging hints then a solution.

  • Are you sure that you don't want generatedId = true for both id fields? Otherwise you are going to need to set the id field's value yourself.
  • Are you sure that f1'd id field is not null as well? Where is that field set? You should log the value of f1.getId() after the insertFamily(...) method returns to make sure the value is an integer.
  • Do you really want the field to be an Integer? Can the id ever be null? I usually use int or long for my id fields.
  • And what is the insertFamily(...) doing? Why aren't you just calling dao.create(...)?

Hope something here helps. Oh and lastly, just say no to Hungarian notation if you can. Use coloration on your IDE to replace it. :-)

Upvotes: 1

Related Questions