3

如您所见,我有两个表(优惠,项目)我在插入项目时遇到问题,每次添加优惠时它都不会插入项目列表。Offer 包含一个项目列表。这是我的代码:

提供:

@Entity
public class Offer{

@Id
@GeneratedValue
int id;
private String name;
private String description;

@OneToMany(mappedBy="offer")
private List<Item> items;
//getters and setters

项目:

@Entity
public class Item{

@Id
@GeneratedValue
int idItem;
private String name;
private double price;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="idOffer")
private Offer offer;
 // getters and setters

这是填写表格的代码:

    Offer offer=GenerateData.generateOffer();
    List<Item> items=new ArrayList<>();
    for(int i=0;i<3;i++){
        Item item=GenerateData.generateItem();
        items.add(item);
        item.setOffer(offer);
    }
    offer.setItems(items);

    pDB.addOffer(offer);//DAO for adding Offers into DB

优惠已成功添加,但商品未成功添加。映射有问题吗?

4

2 回答 2

4

您是否尝试在 OneToMany 端放置级联选项?

于 2013-01-18T17:26:53.937 回答
0

提供

 @OneToMany(cascade = { CascadeType.ALL }, orphanRemoval = true, mappedBy = "offer")
private List<Item> items;

物品:

@ManyToOne
@JoinColumn(name="idOffer")
private Offer offer;
于 2013-01-18T17:33:21.627 回答