I'm trying to do an insert of a parent object (BulkSmsDataset) and its children (BulkSmsRecipient) at once. I use Hibernate 5 and MariaDB 10.1. I should be able to create a BulkSmsDataset and fill the List<BulkSmsRecipientEntity> bulkSmsRecipientEntityList
with new objects then persist the whole thing at once right? But when I try to do that, Hibernate doesn't properly set the FK dataset_id
on the BulkSmsDatasetEntity
objects.
I get the following exception:
Hibernate: insert into bulk_sms_dataset (job_id, name, template) values (?, ?, ?)
Hibernate: insert into bulk_sms_recipient (dataset_id, error_description, processed_on, processing_id, target) values (?, ?, ?, ?, ?)
.....
ERRORS:
SQL Error: 1048, SQLState: 23000
(conn=330108) Column 'dataset_id' cannot be null
Caused by: java.sql.SQLException: Column 'dataset_id' cannot be null
Query is: insert into bulk_sms_recipient (dataset_id, error_description, processed_on, processing_id, target) values (?, ?, ?, ?, ?), parameters [<null>,<null>,<null>,<null>,'+41788718818']
Any idea why this happens? Why is it not setting the dataset_id correctly? Id should first insert the bulk_sms_dataset and then use the ID generated by auto_increment (MariaDB) to set the FKof the bulk_sms_recipient...
I put the code for the entities below.
@Entity
@Table(name = "bulk_sms_dataset")
@Data
@EqualsAndHashCode(exclude = "job")
public class BulkSmsDatasetEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "template")
private String template;
@JoinColumn(name = "job_id")
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private BulkSmsJobEntity job;
@OneToMany(mappedBy = "bulkSmsDatasetEntity", fetch = FetchType.LAZY)
@Cascade({org.hibernate.annotations.CascadeType.ALL})
private List<BulkSmsRecipientEntity> bulkSmsRecipientEntityList;
}
@Entity
@Table(name = "bulk_sms_recipient")
@Data
@EqualsAndHashCode(exclude = "bulkSmsDatasetEntity")
public class BulkSmsRecipientEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "target")
private String to;
@Column(name = "error_description")
private String error;
@Column(name = "processing_id")
private String processingId;
@Column(name = "processed_on", columnDefinition = "timestamp")
@Type(type = "org.hibernate.type.ZonedDateTimeType")
private ZonedDateTime processedOn;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "dataset_id", nullable = false)
private BulkSmsDatasetEntity bulkSmsDatasetEntity;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "recipient_id")
private List<BulkSmsPlaceholderEntity> bulkSmsPlaceholderList;
}