如何通过第三链接两个表?

时间:2019-01-11 10:41:01

标签: spring spring-boot spring-data-jpa

我有三个表:

1)图书:身份证(主要),姓名

2)商店:代码(唯一而不是主要的),名称

3)book_shop:book_id,shop_id(代码),价格

我想在像

这样的书中开店
book.getShop();

如何链接此实体?

我尝试过:

@Data
@NoArgsConstructor
@Entity
@Table(name = "book", schema = "example")
@EntityListeners(AuditingEntityListener.class)
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<BookShop> bookShop;
}

@Data
@NoArgsConstructor
@Entity
@Table(name = "shop", schema = "example")
@EntityListeners(AuditingEntityListener.class)
public class Shop {
    @Id
    private int code;

    private String name;

    @OneToMany(mappedBy = "shop", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<BookShop> bookShop;
}

@Data
@NoArgsConstructor
@Entity
@Table(name = "book_shop", schema = "example")
public class BookShop  implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Id
    @ManyToOne
    @JoinColumn(name = "book_id")
    private Book book;

    @Id
    @ManyToOne
    @JoinColumn(name = "shop_id")
    private Shop shop;

    @Column(name = "price")
    private int fromDate;
}

此代码返回空集:Book book = bookRepostiory.getById(1).get()。getBookShop()

2 个答案:

答案 0 :(得分:0)

尝试如下所示的多对多映射工具,删除book_shop表,

将此代码添加到商店实体,

  @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
  @JoinTable(name = "book_shop",
      joinColumns = {@JoinColumn(name = "book_id", nullable = false)},
      inverseJoinColumns = {@JoinColumn(name = "shop_id", nullable = false)})
  private Set<Book> bookList = null;

将此代码添加到图书实体中,

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, 
mappedBy ="bookList")
    private Set<Shop> shopList=null;

如有问题请告知!

答案 1 :(得分:0)

我建议,首先-在实体中初始化集合

private Set<BookShop> bookShop = new HashSet<>();

第二,例如,将fetch = FetchType.EAGER添加到您的关联中,例如

@OneToMany(fetch = FetchType.EAGER, mappedBy = "book", cascade = CascadeType.ALL)