hguser
hguser

Reputation: 36058

why the one-to-one undirectional mapping exist?

I am learning hibernate,and I am confused by the one-to-one undirectional mapping.

For example: one wife for just one husband and vice versa.

The wife.java:

@Entity
public class Wife {
    private int id;
    private String name;

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}

The Husband.java:

@Entity
public class Husband {
    private int id;
    private String name;
    private Wife wife;
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    @OneToOne
    @JoinColumn(name="wifeId")
    public Wife getWife() {
        return wife;
    }
}

This is a one-to-one undirectional (foreign key) mapping.

Now,my question is:

does this work? How can it make sure that one husband can only have one wife,at this suitation,there may be more than one husband own the same wife.

There is no constrain between the husband and wife.

So I wonder what is the problem?

Upvotes: 1

Views: 588

Answers (3)

axtavt
axtavt

Reputation: 242726

When your relationship is optional (i.e. wife can be null), Hibernate by default doesn't create an unique contraint on foreign key. However, you can make it to create the constraint by using @JoinColumn(..., unique = true) (unless you use the DBMS where unique constraint on nullable column doesn't work as expected, such as DB2 or Ingres).

For required relationships Hibernate creates unique constraint automatically:

@OneToOne(optional = false)
@JoinColumn(name="wifeId")
public Wife getWife() {
    return wife;
} 

Unique constraint enforces one-to-one relationship, because it requires all husbands to have unique wifeIds, thus it requires them to reference different wives.

Upvotes: 3

Satadru Biswas
Satadru Biswas

Reputation: 1595

The JoinColumn in the mapping signifies the column in the Husband table which contains the Identifier to his wife in the Wife table. This column is present in the Husband table, so each husband record can hold only one identifier in the wife column, hence can have only one wife. This however does not implicitly stop the woman from marrying other husband :D. You will have to take care of that yourself. In my opinion, the unique constraint will not allow two records in the Husband table to have the same wifeId, but from an application point of view you should enforce a check before adding or updating a husband object.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691993

You can be sure to have only one husband per wife by putting a unique constraint on the wifeId column. Either put it directly in your database or, if you use hibernate to generate your schema, add the attribute unique="true" to your JoinColumn annotation

Upvotes: 0

Related Questions