I have a problem with persisting new objects to the database. I'm using Eclipselink and Postgresql. When I'm trying to add a new Merchandise, cascade adds also Price object.
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
my code in facede looks like this:
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
This gets mean error (in Polish base so I'll try to translate it): foreign key restriction violation - Key (id)=(356) is not present in merchandises.
I think this is problem with generating id, id fiels is always replaced by generated id, and i think they are different, but in this case should be the same