我试图在订单和订单产品之间实现一对多关联,但我总是遇到此异常:
Foreign key (FKmn6eaqdlnl33lnryjkwu09r0m:order_product_entity [order_id,product_id])) must have same number of columns as the referenced primary key (orders [id])
我知道这意味着什么,但是我不确定应该如何更改方案来解决它。我的设计基于本教程:Spring Java eCommerce Tutorial
除了我的代码是用Kotlin编写的,我无法分辨出差异。
我正在将Spring Boot与Spring Data JPA和Kotlin一起使用。
我的产品实体:
@Entity
@Table(name = "product")
data class ProductEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long,
@NotNull(message = "Product name is required")
var name: String,
var price: Double,
var description: String
)
我的订单实体:
@Entity
@Table(name = "orders")
data class OrderEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id:Long,
var dateCreated:Date,
var status:String,
@JsonManagedReference
@OneToMany(cascade = arrayOf(CascadeType.ALL), mappedBy = "orderProductEntityId")
@Valid
val orderProducts: List<OrderProductEntity>
)
OrderProductEntity:
@Entity
data class OrderProductEntity(
@EmbeddedId
@JsonIgnore
var orderProductEntityId: OrderProductEntityId,
@JsonBackReference
@ManyToOne(optional = false, fetch = FetchType.LAZY)
var order: OrderEntity,
@ManyToOne(optional = false, fetch = FetchType.LAZY)
var product: ProductEntity,
@Column(nullable = false)
var quantity: Int = 0
)
我的复合主键:
@Embeddable
data class OrderProductEntityId(
@Column(name = "order_id")
var orderId: Long = 0,
@Column(name = "product_id")
var productId: Long = 0
) : Serializable
有什么建议吗?
答案 0 :(得分:0)
我相信您使用的是“派生身份”。尝试像这样映射 <div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
<div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
<div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
<div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
<div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
<div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
</div>
:
OrderProductEntity
请注意新的@Entity
data class OrderProductEntity(
@EmbeddedId
@JsonIgnore
var orderProductEntityId: OrderProductEntityId,
@JsonBackReference
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@MapsId("orderId") // maps orderId attribute of embedded id
var order: OrderEntity,
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@MapsId("productId") // maps productId attribute of embedded id
var product: ProductEntity,
@Column(nullable = false)
var quantity: Int = 0
)
批注。
在JPA 2.2 spec的第2.4.1节中讨论了派生的身份(带有示例)。