![](/img/trans.png)
[英]JPA/Hibernate5: How to replace a child object mapped with @OneToOne and @MapsId?
[英]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.