使用 Spring JPA 建立一对多关联

2015/10/30 posted in  Java学习  

一对多单向关联

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

public class User {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String username;
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private Set<Email> emails = new HashSet<>();
}
public class Email {
    @Id
    @GeneratedValue
    private Integer id;
    /* 默认关联字段名为:驼峰类名转为下划线方式 + "_" + @Id 注解的字段名。
    例如 User 的 username 字段有 @Id 注解,则 Email 表关联的字段就默认为 user_username */
    @Column(name = "user_id")
    private Integer userId; 
    @Column
    private String email;
}

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

public class User implements Serializable {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String username;
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_name", referencedColumnName = "username")
    private Set<Email> emails = new HashSet<>();
}
public class Email {
    @Id
    @GeneratedValue
    private Integer id;
    @Column(name = "user_name")
    private Integer userName;
    @Column
    private String email;
}

一对多双向关联

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

public class User {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String username;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    private Set<Email> emails = new HashSet<>();
}
public class Email {
    @Id
    @GeneratedValue
    private Integer id;
    /* 默认关联字段名为:驼峰类名转为下划线方式 + "_" + @Id 注解。的字段名
    例如 User 的 username 字段有 @Id 注解,则 Email 表关联的字段就默认为 user_username */
    @ManyToOne
    private User user;  // 默认表字段为:user_id
    @Column
    private String email;
}

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

public class User implements Serializable {
    @Id
    @Column
    private String username;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    private Set<Email> emails = new HashSet<>();
}
public class Email {
    @Id
    @GeneratedValue
    private Integer id;
    @ManyToOne
    @JoinColumn(name = "user_name", referencedColumnName = "username")
    private User user; // Email 实体对应的表字段为:user_name
    @Column
    private String email;
}