Bastien
Bastien

Reputation: 658

Id vs reference in entity class with persistence

This is a purely theoretical question. Let's say I have an entity Foo linked to an other entity Bar. Obviously both are assigned a unique id, which is used by the persistence system to link them. Should my Foo entity class have a reference to a Bar object or a Bar object id? In code :

class Foo {
    int id;
    Bar bar;
}

or

class Foo {
    int id;
    int barId;
}

This is a pretty basic problem but I wasn't able to find a satisfying answer. This question has very few insights.

The way I see it is that using reference is more along the OOP philosophy but could easily generate null references and performance problems without the use of lazy loading. On the other hand, using id would be faster and easier but could quickly lead to inconsistent data.

So what should one do and why?

If it depends, are there decision factors like entity size, "depth", model complexity...? Or is it only a matter of testing both?

Also could someone point me to some literature reference about this issue?

Upvotes: 3

Views: 1899

Answers (1)

Jeff Miller
Jeff Miller

Reputation: 1434

My experience is that I always need the foreign key so at a minimum, I need:

class Foo {
    int id;
    int barId;
}

Including a reference to Bar depends upon the application. If you are using an ORM, then Foo can have Bar reference as a direct or lazy relationship:

class Foo {
    int id;
    int barId;
    Bar bar;
}

Upvotes: 1

Related Questions