Search code examples
javahibernatejpahibernate-mappingone-to-one

Unique constraint in OneToOne bi-directional mapping


Is unique=true required in bi-directional one-to-one mapping in the owner of the relationship?

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private String name;

    @OneToOne(cascade={CascadeType.PERSIST})
    @JoinColumn(name="passport_id", unique=true) //is unique=true required for bi-directional one-to-one mapping
    private Passport passport;

    public Passport getPassport() {
        return passport;
    }

}

@Entity
public class Passport {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(name="passport_number")
    private String passportNumber;

    @OneToOne(mappedBy="passport")
    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }

}

Hibernate documentation says that FK column in the database should be constrained unique to simulate one-to-one multiplicity, but it doesn't add the unique=true in the bi-directional mapping.


Solution

  • That's because it's not mandatory to use the Hibernate auto DDL feature. You can have incremental schema update scripts and the schema related annotations would be useless. Frankly, we kinda use those for in memory integration testing.

    As you pointed out, the JoinColumn should state the uniqueness constraint.