JPA一对多、多对多配置

单向一对多

@Data
@Entity
@Table(name = "banner")
public class Banner {
    @Id
    private Integer id;

    private String name;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "bannerId", referencedColumnName = "id")
    private List items;
}

上面为单方配置,@JoinColumn注解里面name表示多方中配置的外键属性,referencedColumnName为外键对应的单方主键属性。

@Data
@Entity
@Table(name = "banner_item")
public class BannerItem  {
    @Id
    private Integer id;

    private String img;

    private Integer bannerId;

    private String name;

}

上面为单方配置,没有什么特殊的。

双向一对多

@Data
@Entity
@Table(name = "banner")
public class Banner {
    @Id
    private Integer id;

    private String name;

    @OneToMany(fetch = FetchType.LAZY, mappedBy="banner")
    private List items;
}

双向时单方不需要@JoinColumn注解,需要在@OneToMany上添加mappedBy属性指明多方的映射属性。

@Data
@Entity
@Table(name = "banner_item")
public class BannerItem  {
    @Id
    private Integer id;

    private String img;

    private Integer bannerId;

    private String name;

    @ManyToOne
    @JoinColumn(name="bannerId")
    private Banner banner;

}

多方的注解使用@ManyToOne,标注在映射单方的属性上,同时需要加上@JoinColumn注解指明外键属性。

单项多对多

@Data
@Entity
@Table(name = "student")
public class Student {
    @Id
    private Integer id;

    private String name;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "student_teacher", joinColumns = @JoinColumn(name = "student_id"),
            inverseJoinColumns = @JoinColumn(name = "teacher_id"))
    private List teachers;
}

上面为多方单向配置,@ManyToMany表明多对多,@JoinTable中name为中间表名称,joinColumns属性为中间表中当前表的外键表字段名称,inverseJoinColumns为关联另一个多方的外键外键表字段名称。

@Data
@Entity
@Table(name = "teacher")
public class Teacher {
    @Id
    private Integer id;

    private String name;

    
}

单向多对多中另一个多方不需要特殊配置,由于是单项也不需要导航属性。

双向多对多

@Data
@Entity
@Table(name = "student")
public class Student {
    @Id
    private Integer id;

    private String name;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "student_teacher", joinColumns = @JoinColumn(name = "student_id"),
            inverseJoinColumns = @JoinColumn(name = "teacher_id"))
    private List teachers;
}


@Data
@Entity
@Table(name = "teacher")
public class Teacher {
    @Id
    private Integer id;

    private String name;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy="teachers")
    private List students;
}

双向多对多需要在一个多方的@ManyToMany中配置mappedBy属性为另一方的导航属性,@JoinColumn注解只需在另一方添加。

你可能感兴趣的