Need some help understanding if I’m on the right track here and exactly what I need to do. Hope someone can chime in.
So I’ve got three tables, Job, Authorization, and Filter. Each Job must have one Authorization and one Filter. Of course, each Filter could be used by more than one job and the same goes for the Authorization. However, the Filters and Authorizations don’t need to know what Jobs they are being used by.
So that is a one to many relationship on the part of the Filters and Authorizations I believe right? Or am I off track? How is this modeled in a database? I believe the Job table needs to have a foreign key field to the Filter and Authorization tables. Do the Filter and Authorization tables need foreign key fields themselves to Job?
Next, how do I model this in Java objects and then how do I set up the hibernate or java persistence annotations? I believe the Filter class looks like:
class Filter {
@OnetoMany
@JoinColumn(name="filterID")
private Job job;
}
and the Authorization class basically the same and then how would the Job class look? The thing that’s really throwing me is that the Filter and Authorization classes don’t need any knowledge of what Job they’re associated with so I don’t see the need for them to actually hold references to Job objects. Only the Job class needs to hold references to the Filter and Authorization objects. So do I really need the above code?
I’m hoping someone can help clarify all this for me as I can’t seem to wrap my head around it. Databases are not my strong suit. Thanks.
As far as I know, using a @OneToMany annotation is not very recommended in your situation. Maybe you may want the other side to own the relation.
Check this article out:
http://josian.wordpress.com/2006/09/09/hibernate-annotations-bidirectional-one-to-many/
So, to your question, no, you do not need the above code.
You need something like this:
and on your Filter
EDIT:
The @JoinColumn is just the name you want to appear in your Job table. By default, if you dont specify the join çolumn name, it is going to be {foreignTableName}_id. In the case of Authorizatrion, if you annotated it like this:
the default join column generated for you in the Job table will be
"foo_id"and will reference the"auth_id"field in the"foo"table.TO your final comment:
Actually you don’t need to put foreign keys in the db. In the Job Entity, the
@ManyToOne annotation already ensures the keys will be placed for you. The
@JoinColumnspecifies the names of the foreign key. For example, if you want your foreign key name in the Job table to Authorization to be called ‘authorization_fk’, you would useand this is how it is gonna be placed in your Job table.