我有下面兩個表具有單向關係:@OneToOne上表的主鍵不工作時插入
CREATE TABLE `document` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime NOT NULL,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`partition_key` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`,`partition_key`),
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8
和
CREATE TABLE `document_payload` (
`document_id` int(11) unsigned NOT NULL,
`document_payload` mediumtext,
`partition_key` varchar(20) DEFAULT NULL,
PRIMARY KEY (`document_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
所以這裏DOCUMENT_ID document_payload的列是指id列的文件。現在,我想加入在我的模型類這兩個表,下面的方法:
@Data
@Entity
@JsonSnakeCase
@JsonIgnoreProperties(ignoreUnknown = true)
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String partitionKey;
@OneToOne(fetch= FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name = "id", referencedColumnName = "document_id")
private DocumentPayload documentPayload;
@NotNull
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
@JsonSerialize(using = CustomDateSerializer.class)
private LocalDateTime createdAt;
@PrePersist
public void onCreate() {
createdAt = LocalDateTime.now();
}
}
和
@Data
@Entity
@JsonSnakeCase
@JsonIgnoreProperties(ignoreUnknown = true)
public class DocumentPayload {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "document_id")
private Long documentId;
private String documentPayload;
private String partitionKey;
}
但同時堅持,它拋出以下錯誤:
java.sql.SQLException: Field 'document_id' doesn't have a default value
我試過@PrimaryKeyJoinColumn我使用@joincolumn的方式,但沒有幫助,我想傳播ID爲dcoument_payload表的自動生成的值作爲document_id,我在這裏丟失了什麼?
你如何堅持你的實體? –
使用EntityManager的持久方法。 this.getEntityManager.persist(document) – user2098324
可以分享該代碼 –