I have a problem and I just do not know how to solve it. I want to model in JAVA a structure like: Companies, Events and Locations.
Here's the code:
public class Event {
int id;
String name;
Location location;
...
}
public class Location {
int id;
String name;
String building;
...
}
public class Company {
int id;
String name;
Collection<Location> locations;
...
}
My problem is that i want to use ORMLite for saving the objects in a Database. But if I understood the foreign things in ORMLite correctly, i have to add a Company instance variable to the Location:
public class Location {
@DatabaseField(columnName = "com_id", foreign = true)
Company company;
@DatabaseField(id = true, columnName = "loc_id")
int id;
@DatabaseField(columnName = "loc_name")
String name;
@DatabaseField(columnName = "loc_build")
String building;
...
}
public class Company {
@DatabaseField(columnName = "com_id")
int id;
@DatabaseField(columnName = "com_name")
String name;
@ForeignCollectionField()
Collection<Location> locations;
...
}
But now the Location doesn't work for the Events!?! How can I implement such a behaviour?
Thank you for your answers
Somehow you need to assign "ownership" of a Location
by a Company
. You can do this in (at least) 2 different ways.
As you mentioned, you can have a Location
has a Company
field. This would work fine if there was a one-to-one relationship there. It would not work if you are trying to have one "Pittsburgh"
Location
and you want both "Alcoa"
and "US Steel"
companies having a location in Pittsburgh.
The 2nd way to implement it is to have a CompanyLocation
entity which is often called a join-table in ORM languages. ORMLite does not make this join table for you however.
public class CompanyLocation {
@DatabaseField(foreign = true)
Company company;
@DatabaseField(foreign = true)
Location location;
}
So if want "Alcoa"
to have a Location
of "Pittsburgh"
you need to insert a CompanyLocation
into the table which defines the relationship.
Hope this helps.