简体   繁体   中英

How should I map a unique OneToOne Hibernate relationship?

I have two entities: Credential and Account. Credential entity should have unique e-mail, unique nickname and password, all strings. Account must have one single and unique Credential and other non important attributes. I thought about using e-mail as PK on Credential and on Account. Is this a good approach? I tried to implement that but as you can see here I didn't solve my problem at all. What would be a good coding practice to do this?

Unique OneToOne would be considered a good option? How I should use JPA notations to do so? I know this question can be opinion-based, but I don't even have the options to choose from. I would like to know what basic rules I should follow to implement this concept.

You can just create unique constraint on your database for desired fields. Uniqueness of the fields is don't related to unique mapping. Also you can add unique constraint for your foreign key field - this will ensure that you have oneToOne in the database itself. Check your database documentation for details about how to create constraints.

Use oneToOne like this:

@Entity
public class Account {

    @Id
    private Long id;

    // other fields...
    // some of them are unique

    @OneToOne(mappedBy = "account")
    private Credential credential;
    // omitted

}


@Entity
public class Credential {

    @Id
    private Long id;

    @OneToOne
    private Account account;

}

OneToOne by design is means what it means: for one entity there will be another one entity. So for every account - just one credential.

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