Java Reference
In-Depth Information
Table 7-19. The Picture Table
ID
Advert
Caption
Filename
1
1
My bike (you can ride it if you like)
advert001.jpg
advert002.jpg
2
2
Chesterfield sofa
3
3
MGF VVC (BRG)
advert003.jpg
If we decide (considering the database only) to allow additional pictures, we can then
include extra rows in the Picture table without duplicating any data unnecessarily (see
Table 7-20).
Table 7-20. The Picture Table with Multiple Pictures per Advert
ID
Advert
Caption
Filename
1
1
My bike (you can ride it if you like)
advert001.jpg
advert002.jpg
2
2
Chesterfield sofa
3
2
Back of sofa
advert003.jpg
advert004.jpg
4
3
MGF VVC (BRG)
With the single Advert table, the query to extract the data necessary to materialize an
instance of the Advert consists of something like this:
select id,title,contents,picturecaption,picturefilename from advert where id = 1
It is obvious here that a single row will be returned, since we are carrying out the selection
on the primary key.
Once we split things into two tables, we have a slightly more ambiguous pair of queries:
select id,title,contents from advert where id = 1
select id,caption,filename from picture where advert = 1
While Hibernate is not under any particular obligation to use this pair of SQL instructions
to retrieve the data (it could reduce it to a join on the table pair), it is the easiest way of thinking
about the data we are going to retrieve. While the first query of the two is required to return a
single row, this is not true for the second query—if we have added multiple pictures, we will get
multiple rows back.
In these circumstances, there is very little difference between a one-to-one relationship
and a one-to-many relationship, except from a business perspective. That is to say, we choose
not to associate an advert with multiple pictures, even though we have that option.
This, perhaps, explains why the expression of a one-to-one relationship in Hibernate is
usually carried out via a many-to-one mapping. If you do not find that persuasive, remember
that a foreign key relationship, which is the relationship that the advert column in the Picture
table has with the id column in the Advert table, is a many-to-one relationship between the
entities.
In our example, the Picture table will be maintaining the advert column as a foreign key
into the Advert table, so this must be expressed as a many-to-one relationship with the Advert
object (see Listing 7-6).
Search WWH ::




Custom Search