Hibernate的级联存储

t8e9dugd  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(148)

我还是个新手,我正在尝试使用它的级联功能。我的域名是关于商店和预约的。每个商店都有多个约会,并且每个约会都与一个商店相关联(OneToMany关系)。下面是类声明:

@Entity
@Table(name = "stores")
class Store(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null,

    @Version
    var version: Long = 0,

    @OneToMany(mappedBy = "store", cascade = [CascadeType.PERSIST,CascadeType.REMOVE])
    var appointments: MutableList<Appointment> = mutableListOf(),
);

@Entity
@Table(name = "appointments")
class Appointment(
    @ManyToOne(cascade = [CascadeType.PERSIST])
    var store: Store,
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null,

    @Version
    var version: Long = 0
)

我的服务方法使用了Spring存储库,并执行以下操作:

fun bookAppointment(newAppointment: NewAppointment): Appointment {
        Validators.validateEmail(newAppointment.customer.email)
        val store = storeRepository.findById(newAppointment.storeId).orElseThrow { EntityNotFoundException(Store::class.java) }

        val appointment = store.addAppointment(newAppointment)
        storeRepository.save(store)
        emailService.sendAppointmentBookedEmail(appointment)
        return appointment
    }

但在保存后出现了一些问题。当我在调试中运行时,我看到约会已添加到具有有效值(我作为用户插入的值)的约会集合中。但是在存储调用之后,存储示例更改和约会集合--前一个约会的所有值被设置为空或0,并且只有在这之后,约会才被保存到带有错误数据的数据库中。这可能是什么问题?

9w11ddsr

9w11ddsr1#

而不是重新保存存储(这将导致合并,这就是为什么您在添加Cascade.all时会看到不同的结果,因为这包括Cascade.merge)。您应该创建一个约会存储库并保存约会。

fun bookAppointment(newAppointment: NewAppointment): Appointment {
    Validators.validateEmail(newAppointment.customer.email)
    val store = storeRepository.findById(newAppointment.storeId).orElseThrow { EntityNotFoundException(Store::class.java) }

    val appointment = store.addAppointment(newAppointment)
    appointment.setStore(store);
    appointment = appointmentRepository.save(appointment)
    emailService.sendAppointmentBookedEmail(appointment)
    return appointment
}

// remove cascade from @ManytoOne

@Entity
@Table(name = "appointments")
class Appointment(
    @ManyToOne
    var store: Store,

相关问题