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.
- Each Company includes one or many Location/s which represents the places where a branch of the company is
- Each event also has a Location where the event takes place
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
Locationby aCompany. You can do this in (at least) 2 different ways.As you mentioned, you can have a
Locationhas aCompanyfield. 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"Locationand you want both"Alcoa"and"US Steel"companies having a location in Pittsburgh.The 2nd way to implement it is to have a
CompanyLocationentity which is often called a join-table in ORM languages. ORMLite does not make this join table for you however.So if want
"Alcoa"to have aLocationof"Pittsburgh"you need to insert aCompanyLocationinto the table which defines the relationship.Hope this helps.