我在将新对象持久保存到数据库时遇到问题。我正在使用 Eclipselink 和 Postgresql。当我尝试添加新商品时,级联还会添加 Price 对象。
价格.java
@Entity
@Table(name = "Prices")
public class Price implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false)
private int id;
@Column(updatable = false, nullable = false)
private float value;
@Column(updatable = false, nullable = false)
private Date startDate;
@Column(updatable = false, nullable = true)
private Date endDate;
@ManyToOne(targetEntity=Merchandise.class,cascade=CascadeType.ALL)
@JoinColumn(name="id",nullable = false,updatable = false,insertable=false)
private Merchandise merchandiseId;
@Column(updatable = false, nullable = true)
private float valueBulk;
@Column(updatable = false, nullable = true)
private float valueRetail;
@Column(updatable = false, nullable = true)
private float makeupPercent;
@Column(updatable = false, nullable = true)
private float makeupForce;
Merchandise.java
@Entity
@Table(name="Merchandises")
public class Merchandise implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false)
private int id;
@Column(updatable = false)
private int externalId;
@Column(unique = false, nullable = false, updatable = true)
private String name;
@Column(unique = false, nullable = true, updatable = true)
private int available;
@Column(unique = false, nullable = true, updatable = true)
private String description;
@OneToMany(targetEntity = Price.class, mappedBy = "merchandiseId",cascade = CascadeType.PERSIST)
private List<Price> prices;
@OneToMany(targetEntity = MerchandiseCategory.class, mappedBy = "merchandiseId",cascade = CascadeType.PERSIST)
private List<MerchandiseCategory> merchandiseCategories;
@OneToMany(targetEntity = MerchandiseOrder.class, mappedBy = "merchandiseId",cascade=CascadeType.PERSIST)
private List<MerchandiseOrder> merchandiseOrders;
@OneToMany(targetEntity = MerchandiseDiscount.class, mappedBy = "merchandiseId",cascade=CascadeType.PERSIST) //#61
private List<MerchandiseDiscount> discounts; //#61
我在 facede 中的代码如下所示:
Dao dao = new DAO();//begins transaction etc.
Merchandise m = new Merchandise;
m.set..//setting all needed fields
List<Price> list = new ArrayList<Price>();
Price p = new Price();
p.set..//setting all needed fields
p.setMerchandiseID(m);
list.add(p);
m.setPrices(list);
dao.addMerchandise(m);//persisting
这得到了平均错误(以波兰语为基础,所以我会尝试翻译它):外键限制违规 - 商品中不存在键(id)=(356)。
我认为这是生成 id 的问题,id 字段总是被生成的 id 替换,我认为它们是不同的,但在这种情况下应该是相同的