haps10
haps10

Reputation: 3536

one-to-one mapping using unique constraint not working as expected

I'm trying this simple uni-directional one-to-one relationship

Person ----> Address

using many-to-one mapping with unique constraint.

This is how my mapping looks like in Person.hbm.xml:

<class name="Person" table="PERSON">
<many-to-one name="address" column="ADDRESS_ID" cascade="all" not-null="true" unique="true"/>

I think this should allow only one unique Address per Person - no two Persons can share a common address.

So, the following code should fail. But in this code Hibernate allows both the Johns to stay at same address.

    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();
    Address address = new Address("Bond Street", "London", 121212);
    Person person1 = new Person("John Doe", address);
    Person person2 = new Person("John McClane", address);
    session.save(person1);
    session.save(person2);
    transaction.commit();
    session.close();

Please let me know what am I missing here?

Upvotes: 3

Views: 1658

Answers (1)

JB Nizet
JB Nizet

Reputation: 691735

Read http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#d0e7576, and find the many-to-one description in paragraph 5.1.7.1. It says :

unique (optional): enables the DDL generation of a unique constraint for the foreign-key column. By allowing this to be the target of a property-ref, you can make the association multiplicity one-to-one.

This means that it's used by the database schema generation tool of Hibernate to add a unique constraint. If you don't use it, then you must add this constraint yourself.

Upvotes: 4

Related Questions