Hibernate和MariaDB auto_increment未使用层叠正确设置FK

时间:2019-05-06 15:11:16

标签: java mysql hibernate jpa mariadb

我正在尝试一次插入父对象(BulkSmsDataset)及其子对象(BulkSmsRecipient)。我使用Hibernate 5和MariaDB 10.1。我应该能够创建BulkSmsDataset并用新对象填充List<BulkSmsRecipientEntity> bulkSmsRecipientEntityList,然后立即保留整个对象,对吧?但是,当我尝试这样做时,Hibernate并没有在dataset_id对象上正确设置FK BulkSmsDatasetEntity

我收到以下异常:

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']

知道为什么会这样吗?为什么不能正确设置dataset_id? ID应该首先插入bulk_sms_dataset,然后使用auto_increment(MariaDB)生成的ID来设置bulk_sms_recipient的FK ...

我在下面放置了实体的代码。

@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;

}

1 个答案:

答案 0 :(得分:0)

我能够解决此问题。

我必须将@JoinColumn(name = "dataset_id")添加到private List<BulkSmsRecipientEntity> bulkSmsRecipientEntityList;