Hi,
i am trying to insert/update a collection in cascade. i already saw the samples provided in the documentation.
Quote:
Parent p = .....;
Child c = new Child();
p.getChildren().add(c);
session.save(c);
session.flush();
In this case the child is added to the collection of the parent an then the child is saved. What I am trying to do is to set the Children collection (parent.setChildren(
collection of children)) and then to save the parent. The children will be saved automatically due to the relationship they have.
I am using EJB3 and annotations.
Sample:
Code:
public void save()
{
List<Child> children = new ArrayList<>(Child);
Parent p = new Parent();
Child c = new Child();
children.add(c);
p.setChildren(new HashSet<Child>(children));//Child in Parent = Set<Child> rgPositions = new HashSet<Child>(0)
}
public void saveParent(Parent p)
{
entityManager.persist(p);
}
These are the entites:
Code:
public class Child
{
//Variables here
@ManyToOne(fetch = FetchType.LAZY, cascade=CascadeType.ALL)
@JoinColumn(name = "PARENT_ID", nullable = false, insertable = true)
@NotNull
public Parent getParent() {
return this.parent;
}
public void setParent(Parent p) {
this.parent = p;
}
}
public class Child
{
//Variables here
@ManyToOne(fetch = FetchType.LAZY, cascade=CascadeType.ALL)
@JoinColumn(name = "PARENT_ID", nullable = false, insertable = true)
@NotNull
public Parent getParent() {
return this.parent;
}
public void setParent(Parent p) {
this.parent = p;
}
}
public class Parent
{
//Variables here
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parent")
@org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public Set<Child> getChildren() {
return this.rgPositions;
}
public void setChildren(final Set<Child> rgPositions) {
this.children = children;
}
}
When run this code I get an Exception:
Quote:
org.hibernate.PropertyValueException: not-null property references a null or transient value: package.name.Child.parent
I know that at the moment the parent is saved the children in the collection have a null as parent. But I thought that cascade is also bidirectional. I do not have a lot of experience with Hibernate, so I will appreciate any help.
is it possible to do this in this way? or am I doing doing something wrong.
Thanks a lot