Reputation: 356
I have questions about
What are the benefits of using a one-to-one
association on foreign key or a one-to-one
association on the primary key?
I've read the documentation of Hibernate available at: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/associations.html#assoc-unidirectional-121
Can someone tell me with details the plus of using the first or the second implementation?
Another question, I have a one-to-one
unidirectional relationship between User and Perimeter.
(User ----> Perimeter) and I want to use the association based on the foreign key.
Could I reverse the direction into (User <---- Perimeter) so the table User stay intact?
I think that is not reasonable (perimeter.getUser() !!!) but it's technically possible?
Upvotes: 2
Views: 15437
Reputation: 5005
one to one relationship using primary key association
In this association one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity.
here is the link for example: primary key association
one to one relationship using foreign key association
In the same example do the following changes:
In StockDetail.java
private Integer stockDetailsId;
//with setter and getter
//remove stockId and it's setter and getter
in stock.hbm.xml
<id name="stockId" type="java.lang.Integer">
<column name="STOCK_ID" />
<generator class="assigned" />
</id>
in StockDetail.hbm.xml
<id name="stockDetailsId" type="java.lang.Integer">
<column name="STOCK_DETAILS_ID" />
<generator class="assigned"/>
</id>
<many-to-one name="stock"
class="com.test.common.Stock" column="STOCK_ID" />
in hibernate.cfg.xml
//this is optional property if you want to create database table's according to your hbm file's.
<property name="hibernate.hbm2ddl.auto">create</property>
Upvotes: 1
Reputation: 356
In addition to advantages mentioned by JB Nizet and thanks to another person told me that the one-to-one based on foreign key is more flexible. let's consider that i use a one-to-one on foreign key (User <--- Perimeter) , if the requirements of the application changes to need multiple Users for any Perimeter, If i shared the primary key, I'll have much more refactoring to do. But as i used the foreign key, all i do is relax the unique constraint ;)
Upvotes: 3
Reputation: 692161
I see two advantages
For your second question, yes, of course it's possible. That is called a bidirectional OneToOne association:
public class User {
// ...
@OneToOne
@JoinColumn
private Perimeter perimeter;
}
public class Perimeter {
// ...
@OneToOne(mappedBy = "perimeter")
private User user;
}
Upvotes: 3