reset password
Author Message
jigar_gaglani
Posts: 16
Posted 23:03 Apr 21, 2009 |

Hello Professor,

                     In case I write one-to-one association statement in hbm.xml for a class & execute the hbm2ddl target it builds successfully and generates the create statements for table of that class but does not include that particular associated variable in create statement.

                      What can be the reason for that?

 

For eg :

for class "abc" i have abc.hbm.xml in which i wrote :

<one-to-one name="xyz" class="pqr"/>

so in create statement it does not include the column for "xyz".

 

I hope i am clear about my question.

 

Jigar.

cysun
Posts: 2935
Posted 09:45 Apr 22, 2009 |

If you use <one-to-one>, Hibernate assumes that both classes have the same primary key value, so there's no foreign key column. This is refered to as a "primary key one-to-one association" in Hibernate. And to make it work correctly, you need to use a special id generator <generator class="foreign"> (instead of <generator class="native"> that we usually use).

Primary key one-to-one associations are quite rare. A more common case is "unique foreign key one-to-one association", and to map this type of association, you use <many-to-one> with an attribute unique="true".

Consider an example of Forum and last Post - they have an one-to-one relationship because each post belongs to one forum and one forum has only one last post. Note that in this case we must use foreign key one-to-one association because if we make the primary key of Post depend on the primary key of Forum, it means each forum would have only one post; and if we make the primary key of Forum depend on the primary key of Post, it means we need to create some posts before we create the forums.

Now consider User and Blog, where each user has one blog (or no blog) and each blog belongs to exactly one user. In this case both types of one-to-one associations can be used. In particular, if you use primary key one-to-one association, you can make the primary key of Blog depend on the primary key of User.

So generally speaking, which types of one-to-one associations to use depends on the application logic. However, with that said, I always perfer using unique foreign key one-to-one association because a) it can be used for all cases, unlike primary key one-to-one association which doesn't work for some cases (e.g. Forum and last Post); b) it's easier to create the mapping (i.e. no need for <generator class="foreign">); and c) probably most importantly, it makes intuitive sense to a database person like me, because in databases you usually use foreign key constraints to ensure refrential integrity instead of relying on the assumption that primary key values would remain identical.

For further readings:

Last edited by cysun at 09:46 Jul 13, 2010.