Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-to-Many Unidirectional Parent-Child ID Cascade Save

When trying to save an ID from my parent class into a child class, I keep getting the error "ERROR - Field 'parent_id' doesn't have a default value"

I have tried all types of mappings. I am using annotations.

Any help on this would be appreciated

Parent:

      @Id
      @Column(name="id")
      @GeneratedValue(strategy=GenerationType.AUTO)
      private long id;
      @Column(name="description")
      private String description;
      @OneToMany
      @Cascade(value= {org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE})
      @JoinColumn(name="parent_id")
      private List<Child> children;

Child:

  @Id
  @Column(name="id")
  @GeneratedValue(strategy=GenerationType.AUTO)
  private long id;
  @Column(name="description")
  private String description;

Thanks.

like image 710
ButtersB Avatar asked Nov 28 '22 03:11

ButtersB


1 Answers

A late addition in case anyone ever runs into the same issue.

This entity here, when persisted using Hibernate 4.1.8, will cascade the FieldChangeentities, but will not fill the join column:

@Entity
public class Event {

    //ID and other fields here

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "event_id")
    private List<FieldChange<?>> fields = new ArrayList<FieldChange<?>>();

 }

Neither does the insert statement set the event_id column, nor does it update the inserted entity after the fact - the event_id remains null and the relation is lost.

If, however, the @JoinColumn definition is changed like this:

@JoinColumn(name = "event_id", nullable = false)

, then the insert statement includes the event_id column like it should, and all is well.

This may only be a regression in this particular version of Hibernate, but maybe it helps someone.

like image 132
Henning Avatar answered Dec 05 '22 17:12

Henning