gpt4 book ai didi

java - Hibernate 和 MariaDB auto_increment 未通过级联正确设置 FK

转载 作者:行者123 更新时间:2023-11-29 16:03:00 32 4
gpt4 key购买 nike

我正在尝试立即插入父对象 (BulkSmsDataset) 及其子对象 (BulkSmsRecipient)。我使用 Hibernate 5 和 MariaDB 10.1。我应该能够创建一个 BulkSmsDataset 并填写 List<BulkSmsRecipientEntity> bulkSmsRecipientEntityList使用新对象然后立即保留整个事情,对吗?但是当我尝试这样做时,Hibernate 没有正确设置 FK dataset_id关于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;

}

最佳答案

我能够解决这个问题。

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

关于java - Hibernate 和 MariaDB auto_increment 未通过级联正确设置 FK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007933/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com