Good design of mapping Java Domain objects to Tables (using Hibernate)
Posted
by M. McKenzie
on Stack Overflow
See other posts from Stack Overflow
or by M. McKenzie
Published on 2010-05-20T08:34:02Z
Indexed on
2010/05/20
8:40 UTC
Read the original article
Hit count: 244
Hey guys,
I have a question that is more in the realm of design, than implementation. I'm also happy for anyone to point out resources for the answer and I'll gladly, research for myself.
Highly simplified Java and SQL:
Say I have a business domain POJO called 'Picture' with three attributes.
class Picture int idPicture String fileName long size
Say I have another business domain POJO called "Item" with 3 attributes
Class Item int idItem String itemName ArrayList itemPictures
These would be a normal simple relationship. You could say that 'Picture' object, will never exist outside an 'Item' object. Assume a picture belongs only to a specific item, but that an item can have multiple pictures
Now - using good database design (3rd Normal Form), we know that we should put items and pictures in their own tables. Here is what I assume would be correct.
table Item int idItem (primary key) String itemName
table Picture int idPicture (primary key) varchar(45) fileName long size int idItem (foreign key)
Here is my question: If you are making Hibernate mapping files for these objects. In the data design, your Picture table needs a column to refer to the Item, so that a foreign key relation can be maintained. However,in your business domain objects - your Picture does not hold a reference/attribute to the idItem - and does not need to know it. A java Picture instance is always instantiated inside an Item instance. If you want to know the Item that the Picture belongs to you are already in the correct scope. Call myItem.getIdItem() and myItem.getItemPictures(),and you have the two pieces of information you need.
I know that Hibernate tools have a generator that can auto make your POJO's from looking at your database. My problem stems from the fact that I planned out the data design for this experiment/project first. Then when I went to make the domain java objects, I realized that good design dictated that the objects hold other objects in a nested way. This is obviously different from the way that a database schema is - where all objects(tables) are flat and hold no other complex types within them. What is a good way to reconcile this?
Would you: (A) Make the hibernate mapping files so that Picture.hbm.xml has a mapping to the POJO parent's idItem Field (if it's even possible) (B) Add an int attribute in the Picture class to refer to the idItem and set it at instantiation, thus simplifying the hbm.xml mapping file by having all table fields as local attributes in the class (C) Fix the database design because it is wrong, dork.
I'd truly appreciate any feedback
© Stack Overflow or respective owner