繁体   English   中英

使用@MapsId 时,由于 SQL INSERT 中缺少 JPA OneToOne 关系 FK,Hibernate 抛出“列不允许为 NULL”

[英]Hibernate throws "NULL not allowed for column" as the JPA OneToOne relation FK is missing in the SQL INSERT when using @MapsId

在我的 OneToOne 关系中,我得到: NULL not allowed for column "USER_ID"; SQL statement: insert into customer_order (id, enabled, orden_id) values (null, ?, ?) NULL not allowed for column "USER_ID"; SQL statement: insert into customer_order (id, enabled, orden_id) values (null, ?, ?)

它实际上是null因为它不存在于INSERT查询中。 但是,在执行save(customerOrder)时,值USER会填充到customerOder实体中。

@Getter
@SuperBuilder
@MappedSuperclass
@NoArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public abstract class AbstractEntity {

    @Id
    @EqualsAndHashCode.Include
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Setter
    @Default
    @Column(columnDefinition = "BOOLEAN DEFAULT 'true'", nullable = false)
    private Boolean enabled = Boolean.TRUE;
}

@Getter
@Setter
@Entity
@Table(name = "customer_order")
@SuperBuilder
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
public class CustomerOrderEntity extends AbstractEntity {

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId("id")
    private UserEntity user;

       //other values
}

@Data
@Entity
@Table(name = "user")
@SuperBuilder
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
public class UserEntity extends AbstractEntity {

    @NaturalId
    @EqualsAndHashCode.Include
    @Column(length = 28, unique = true, nullable = false)
    private String uuid;

//other values
}

我希望customerOrder与填充的数据一起保存在数据库中。

您的代码完全按照您指定的方式工作。

如果你有一个共享键(你使用@MapsId),Hibernate 不会为外键使用单独的列。 这就是插入查询不包含user_id列的原因。

最重要的是,CustomerOrderEntity 中的 id 一方面是自动生成的(在超类中定义),另一方面是另一个实体的映射 id。 这些是相互矛盾的要求。

使用@MapsId允许您将子表主键用作父表主键的外键。

如果启用hbm2ddl工具,您将看到customer_order表将不包含user_id列。

但是,由于您之前生成了数据库架构并且您有一个带有专用user_id列的customer_order表,那么您需要删除@MapsId

@OneToOne(fetch = FetchType.LAZY)
private UserEntity user;

这样, user关联将使用user_id外键列。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM