JPA:对生成的JoinTable的引用

问题描述 投票:1回答:2

我有两个实体: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)?

问候

java jpa entity-relationship
2个回答
0
投票

要表示特定Product中的Aisle,您需要另一个实体。这是一个例子:

@Entity 
public class Product{
   @Id
   private Long id;
   private String name;
   @OneToMany(mappedBy = "product")
   private Set<ProductAisle> productAisle = new HashSet<>;
   /* getters, setters, equals and hashcode */
}


@Entity 
public class Aisle{
   @Id
   private Long id;
   private String row;
   private String shelf;
   @OneToMany(mappedBy = "aisle")
   private Set<ProductAisle> productAisle = new HashSet<>();
   /* getters, setters, equals and hashcode */
}

@Entity 
public class ProductAisle{
   @Id
   private Long id;
   @ManyToOne(fetch = FetchType.LAZY)
   private Product product;
   @ManyToOne(fetch = FetchType.LAZY)
   private Aisle aisle;
   /* getters, setters, equals and hashcode */
}

然后你的Salesman将指向一个ProductAisle实例的集合,它将产品映射到过道:

@Entity 
public class Salesman{
   @Id
   private Long id;

   private String name;

   @ManyToOne(fetch = FetchType.LAZY)
   private Set<ProductAisle> productAisle;

}

0
投票

由于AisleProduct都有双向映射,你可以将它们中的任何一个(甚至两者)加入Salesman类,你根本不需要加入服务表。

© www.soinside.com 2019 - 2024. All rights reserved.