简体   繁体   中英

Hibernate OneToOne behaving like ManyToOne

I have these classes:

public class Person {

    @Id
    private int personId;

    @OneToOne
    private SomeOtherId someOtherId;
}

public class SomeOtherId {
     @Id 
     private int someId;

     // other fields
}

I did this:

Person person1 = new Person(1);
SomeOtherId someOtherId = new SomeOtherId(100);
person1.setSomeOtherId(someOtherId);
//Update the database so that both the above entities are persisted

Person person2 = new Person(2);
person2.setSomeOtherId(someOtherId);
//Update the database so that person2 is persisted

It all works! And it assigns someOtherId to both the person entities which it shouldn't as the relationship is OneToOne. Each person has to have a unique SomeOtherId. In database also, I can see a single entity for SomeOtherId and id of that mapped to two Persons.

What am I missing here?

您必须添加@JoinColumn并将unique属性设置为true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM