问题
I am creating a schema. My schema is as follows
@Entity
@Table(name = "PROMOTION")
public class Promotion {
@Id
@Column (name = "promotion_id")
private String promotionId;
@JoinColumn(name = "seller_id")
private List<Seller> sellerList;
};
@Entity
@Table(name = "SELLER")
public class Seller {
@Id
@Column (name = "seller_id")
private String sellerId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "promotion_id")
private Promotion promotion;
@ManyToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "seller_id", referencedColumnName = "seller_id")
private List<SellerPromotion> sellerList;
};
@Entity
@Table(name = "SELLER_PROMOTION")
public class SellerPromotion {
@Id
@Column (name = "seller__promotion_id")
private String sellerPromotionId;
@Column(name = "seller_id")
private String sellerId;
@Column(name = "product_id")
private String productId;
};
Problem is when I am executing the Unit Test I am observing that rather than 3, total 4 tables are getting created.
- PROMOTION
- SELLER
- SELLER_PROMOTION
- SELLER_SELLER_PROMOTION
I am not sure how the 4. one is getting created. It is a mapping table which is getting created. Even when I do a show sql, I am able to see that hibernate is making joins with this table (SELLER_SELLER_PROMOTION) before actually joining with SELLER_PROMOTION.
I don't have any clue what is happening. Can anybody please help me understand why it is happening and how to fix this ?
回答1:
The reason why you are getting this is because you have ManyToMany relationship between your Seller and SellerPromotion entities. And only way to model a many to many relation is to have join table. That is why hibernate will create a table with the name SELLER_SELLER_PROMOTION and have two columns as per your case. Each will be foreign key to respective tables.
If you are really interested. Get hold of the book called Pro JPA. It explains these concepts beautifully in capter Object relational mapping.
来源:https://stackoverflow.com/questions/26559731/hibernate-creating-unwanted-mapping-tables