ManyToMany cascade relationship alternative
I have an Auction and an Item class having a many to many relationship with each other.
public class Auction implements BaseEntity,Comparable<Auction>{
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "auction_id")
private Long auctionId;
@Basic(optional = false)
@Column(name = "auction_name")
private String auctionName;
@ManyToMany
@JoinTable(name = "auction_items", joinColumns = {
@JoinColumn(name = "auction_id", referencedColumnName = "auction_id")}, inverseJoinColumns = {
@JoinColumn(name = "item_id", referencedColumnName = "item_id")})
private List<Item> itemList;
...开发者_如何转开发..}
public class Item implements BaseEntity{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="item_id")
private long itemId;
@Column(name="item_name")
private String itemName;
public class Item implements BaseEntity{
private static final long serialVersionUID = 1L;
@ManyToMany
@JoinTable(name="auction_items",joinColumns={@JoinColumn(name="item_id")},inverseJoinColumns={@JoinColumn(name="auction_id")})
private List<Auction> auctionList;
}
While creating a new Auction, sometime I want to pick an existing Item and associate with new Auction and sometimes, a new Item to be created.
If I use (cascade=CascadeType.ALL
) relationship as shown
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name = "auction_items", joinColumns = {
@JoinColumn(name = "auction_id", referencedColumnName = "auction_id")}, inverseJoinColumns = {
@JoinColumn(name = "item_id", referencedColumnName = "item_id")})
private List<Item> itemList;
Then, I'll not be able to associate existing item with new Auction instance and if I don't use this cascade relationship then I'll not be able to create a new item with new Auction.
Can someone please give suggestions on any feature of Spring that provides such flexibility?
The many-to-many relationship can (and should) be changed for a one-to-many relationship. Auctions should be able to contain many items but it makes no sense to have an item in many auctions; what you probably tried was having an item-name in multiple auctions. Example:
You want the item-name "Car" in many auctions, because you have many cars to sell, however think of every single car as a separate entity, the item-identity "Car37191", that black Mercedes can only be in one auction.
精彩评论