JPA :对生成的 JoinTable 的引用

我有两个实体:Product 和 Aisle。一个产品可以在一个或多个通道中,一个通道可以有一个或多个产品。


@Entity 

public class Product{

   @Id

   private Long id;

   private String name;

   @ManyToMany

   @JoinTable(name = "product_aisle",

            joinColumns = { @JoinColumn(name = "product_id") },

            inverseJoinColumns = { @JoinColumn(name = "aisle_id") })

    private Set<Aisle> aisles = new HashSet<>();

   /* getters, setters, equals and hashcode */

}



@Entity 

public class Aisle{

   @Id

   private Long id;

   private String row;

   private String shelf;

   @ManyToMany(mappedBy="aisles")

   private Set<Product> products = new HashSet<>();

   /* getters, setters, equals and hashcode */

}

我还有最后一个实体:推销员。销售员负责过道中的产品:


@Entity 

public class Salesman{

   @Id

   private Long id;


   private String name;


   /* ManyToOne to  ProductAisle ?*/


}

问题:如何使用“@ManyToOne”注释将销售员引用到自动创建的连接表 (ProductAisle)?


梦里花落0921
浏览 250回答 2
2回答

汪汪一只猫

要表示Product特定中的 a,Aisle您需要另一个实体。这是一个例子:@Entity&nbsp;public class Product{&nbsp; &nbsp;@Id&nbsp; &nbsp;private Long id;&nbsp; &nbsp;private String name;&nbsp; &nbsp;@OneToMany(mappedBy = "product")&nbsp; &nbsp;private Set<ProductAisle> productAisle = new HashSet<>;&nbsp; &nbsp;/* getters, setters, equals and hashcode */}@Entity&nbsp;public class Aisle{&nbsp; &nbsp;@Id&nbsp; &nbsp;private Long id;&nbsp; &nbsp;private String row;&nbsp; &nbsp;private String shelf;&nbsp; &nbsp;@OneToMany(mappedBy = "aisle")&nbsp; &nbsp;private Set<ProductAisle> productAisle = new HashSet<>();&nbsp; &nbsp;/* getters, setters, equals and hashcode */}@Entity&nbsp;public class ProductAisle{&nbsp; &nbsp;@Id&nbsp; &nbsp;private Long id;&nbsp; &nbsp;@ManyToOne(fetch = FetchType.LAZY)&nbsp; &nbsp;private Product product;&nbsp; &nbsp;@ManyToOne(fetch = FetchType.LAZY)&nbsp; &nbsp;private Aisle aisle;&nbsp; &nbsp;/* getters, setters, equals and hashcode */}然后您Salesman将指向一组ProductAisle实例,这些实例将产品与通道映射:@Entity&nbsp;public class Salesman{&nbsp; &nbsp;@Id&nbsp; &nbsp;private Long id;&nbsp; &nbsp;private String name;&nbsp; &nbsp;@ManyToOne(fetch = FetchType.LAZY)&nbsp; &nbsp;private Set<ProductAisle> productAisle;}

人到中年有点甜

由于两者Aisle和 相互之间Product具有双向映射,因此您可以将它们中的任何一个(甚至它们两个)加入到Salesman类中,而您根本不需要加入服务表。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java