I'm trying to do something with JPA that'll use a lot on a project but I'm stuck.
I have 2 entities + a kind of "glue" entity, I'll call them
I want to add a new ClassA with new Glues set in it's list, ClassB's already exist.
That would do something like :
ClassA 1 | Glue 1 1 | ClassB 1 ClassA 1 | Glue 1 2 | ClassB 2 ClassA 1 | Glue 1 3 | ClassB 3 ClassA 1 | Glue 1 4 | ClassB 4
So as said ClassA and all Glues are to be inserted, ClassA has a List with the new Glues to be inserted.
Here they are :
@Entity
public class ClassA implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
(...)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "classA")
private List<Glue> glueList;
(...)
}
@Entity
public class ClassB implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
(...)
}
@Entity
public class Glue implements Serializable {
@EmbeddedId
protected GluePK gluePK;
@JoinColumn(name = "id_class_a", referencedColumnName = "id", nullable = false, insertable = false, updatable = false)
@ManyToOne(optional = false)
private ClassA classA;
@JoinColumn(name = "id_class_b", referencedColumnName = "id", nullable = false, insertable = false, updatable = false)
@ManyToOne(optional = false)
private ClassB classB;
(...)
}
@Embeddable
public class GluePK implements Serializable {
@Basic(optional = false)
@NotNull
@Column(name = "id_class_a", nullable = false)
private int idClassA;
@Basic(optional = false)
@NotNull
@Column(name = "id_class_b", nullable = false)
private int idClassB;
(...)
}
When I try to persist my ClassA I'm getting something like :
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot add or update a child row: a foreign key constraint fails (bdd
.glue
, CONSTRAINT constraint_name
FOREIGN KEY (id_class_a
) REFERENCES ClassA
(id
) ON DELETE NO ACTION ON UPDATE NO ACTION)
I understand that he complains that Glues dont have ClassA's reference set but I'd like him to fill it just then he persists ClassA.
Is this achievable? If not what's the best way to do it?
I'd like to stay on JPA without any specific vendor tricks (I'm using eclipselink) but if some vendor can do it easily I'll go for it.
Thanks!
I would remove the EmbeddedId, use an IdClass instead and just add the @Id to the @ManyToOne mappings.
See, http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#JPA_2.0
Or maybe even give Glue an id of its own.
You could also remove the insertable = false, updatable = false from the @ManyToOne and move them to the EmbeddedId.