Spring Data JPA 一对一关联

2015/11/25 posted in  Spring Boot comments

使用注意

User user = new User();
user.setUsername("foo");
Email email = new Email();
email.setUser(user);  // 必须显示设置 user,否则关联字段值会为空
email.setEmail("foo@bar.com");
user.setEmail(email); 
userRepository.save(user);

通过 @Id 注解指定的字段进行关联

public class User {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String username;
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "user")
    private Email email;
}
public class Email {
    @Id
    @GeneratedValue
    private Integer id;
    @OneToOne
    private User user; // 默认表字段为:user_id,字段对应规则和一对多一样
    @Column
    private String email;
}

通过手动指定两边的字段名称

public class User {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String username;
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "user")
    private Email email;
}
public class Email {
    @Id
    @GeneratedValue
    private Integer id;
    @OneToOne
    @JoinColumn(name = "user_name", referencedColumnName = "username")
    private User user;  // Email 实体对应的表字段为:user_name
    @Column
    private String email;
}