1

i have 2 class. Parent and child. as follows:

@Entity
@Table(name = "parent")
public class Parent implements Serializable {
    private String name;
    private List<Child> childs;

    @OneToMany(mappedBy="parent")
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
    public List<Child> getChilds() {
        return childs;
    }
    @Id
    @Column(name="parent_name")
    public String getName() {
        return name;
    }    

}

>

@Entity
@Table(name = "child")
public class Child implements Serializable {

    @JoinColumn(name="parent_name")
    private Parent parent;

    public Parent getParent() {
        return parent;
    }

    public void setParent(Parent parent) {
        this.parent = parent;
    }

}

when i use session.save(parent) it saves parent and child in the database but the column of parent identifier in child table will remain null. so what is the problem?

abozar
  • 175
  • 6
  • 14

2 Answers2

0

try this on child Entity:

 @ManyToOne(targetEntity = Parent.class)

 @JoinColumn(name = "parent", nullable = false)
RAS
  • 8,100
  • 16
  • 64
  • 86
Jorge Iten Jr
  • 366
  • 6
  • 21
  • nothing changed. just an error about sql constraint violation : org.hibernate.exception.ConstraintViolationException: Column 'parent' cannot be null – abozar Jun 25 '13 at 15:21
  • 1
    I don't think hibernate will refresh the child when saving the parent. You could do it by yourself, like this: public void addChild(Child child) { this.childs.add(child); child.setParent(this); } – Jorge Iten Jr Jun 25 '13 at 17:28
  • when i commit the transaction, hibernate will send query to fill columns such this(parent column in child table). so i think it is because i declared parent by myself in child and hibernate will no longer has the responsibility to fill it when commit. any way i will try fill it by my own if not any other opinion exist. – abozar Jun 26 '13 at 04:41
0

If I declare OneToMany as Unidirectional, it works well.

Ry-
  • 218,210
  • 55
  • 464
  • 476
abozar
  • 175
  • 6
  • 14