I got 3 tables on my DB: Articles, Orders and OrderDetails
Article has the item name, the price, and some other information. Orders has the total price for that order and the time when it was placed.
On my OrderDetails table I have the articles that were purchased in certain order using foreign keys to my order and article tables.
The thing is, I don't know how to make this one-to-many relation using Hibernate.
I need to, let's say, retrieve Order #5 and at the same time retrieve all Articles that were purchased in that order and place them in a List of my Order object.
What I get stuck in is, how can I tell Hibernate to look for Order #5 and get ALL rows from OrderDetails and given the ArticleID on OrderDetail, go to the Article table and create an Article object for each one and then place them on a List on my Order object.
If I were using plain old SQL I could do it, but I can't figure out how to make it using HQL and setting each article as an object given that the articles themselves are on a different table.
There are basically two approaches: programmatic or database-oriented (basically the two ways how to use Hibernate: object-oriented or query-oriented).
Programmatic is the "lazy" way. Just define the associations, sometimes as collections, and access them in code. This, obviously, can lead to a lot of db queries when accessing joined tables. Typically a collection will be lazily instantiated, so when you access it the first time your object can't be detached and it will produce a lot of additional database queries. (This is a "trick": Just do a .size() on a collection when the object is not detached to initialize it.)
The other way with queries is to use a "join fetch", as explained here. You can get all associated entities with one query.
The issue I'm having it's I don't know how to make Hibernate do the following (with its respective mapping):
Get me all articles (as Objects) on the articles table corresponding to X Order (also an object, where X is the ID).
It's seems easy, except, the order-article relation is on another table.
So, Hibernate has to, example:
Get Order Object where ID = 5, now go to my OrderDetails table, fetch all Articles IDs and given those IDs go to the Articles table and fetch the corresponding Object. Articles objects need to be saved on a List on the Order object.
It's the middle part that I get stuck at. How to make hibernate not only get the IDs on OrderDetails but also given those IDs fetch the corresponding object from Articles and add them to a List on Orders.