一对多外键必须与引用的主键具有相同的列数

问题描述 投票:0回答:1

我正在尝试在订单和订单产品之间实现一对多的关联,我总是遇到这个异常:

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>
)

订购产品实体:

@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

有什么建议?

spring jpa kotlin hibernate-mapping
1个回答
0
投票

我相信你正在使用“衍生身份”。尝试映射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
)

请注意新的@MapsId注释。

在2.4.1节中的JPA 2.2 spec中讨论了派生身份(带有示例)。

© www.soinside.com 2019 - 2024. All rights reserved.