【问题标题】:Update/Merge all fields of a detached entity with new instance of same class - in Spring Boot使用同一类的新实例更新/合并分离实体的所有字段 - 在 Spring Boot 中
【发布时间】:2019-01-10 04:29:45
【问题描述】:

我已经实现了以下继承。

abstract Superclass: ConnectionTechnologyDetails
Subclasses: SMTPDetails, AS2Details and FTPDetails

子类的实例保存在 Spring 的 JPA 存储库中。新数据来自前端表单,保存在子类的新实例中。

不幸的是,我无法使用新实例的字段更新持久化的实体。因为我不知道实例的实际类,所以我不能使用它们的设置器。只有超类 ConnectionTechnologyDetails 的设置器可用。

// getting the id of the persisted entity
Long connectionTechnologyDetailsDetachedId = connectionPersisted.getConnectionTechnology()
    .getConnectionTechnologyDetails()
    .getId();

// detach the persistent entity
ConnectionTechnologyDetails connectionTechnologyDetailsDetached = 
    connectionTechnologyDetailsRepository
    .findById(connectionTechnologyDetailsDetachedId).get();

我想这样更新:

/** Update all fields with the fields of the 
*   new instance because I can't access
*  the setters and getters of the subclasses here.
*/

connectionTechnologyDetailsDetached
    .updateALlFieldsWith(
        connectionRequest
        .getConnectionTechnology()
        .getConnectionTechnologyDetails()
    );
connectionTechnologyDetailsRepository.save(connectionTechnologyDetailsDetached);

是否有一些方法可以更新所有字段,或者是否有可能访问子类的 setter 和 getter?

到目前为止我的解决方案:从子类的 DiscriminatorColumn 注释中获取特定的子类。然后强制转换到特定的类并使用新值手动调用所有设置器。

【问题讨论】:

  • 有趣的解决方案。因此,您会将所有内容都拉到超类中,而不是例如将其转换为正确的子类?你确定这是一个聪明的主意吗?
  • 我想我会投。因此,我必须在哪个类中转换的信息可在 Annotation DiscriminatorColumn 中找到。但是合并所有字段的方法会更有效,因为我必须写下对 setter 的调用。
  • 任何BeanUtils 或类似的都可以让您将属性从一个对象复制到另一个对象。
  • 哦,好吧,酷!我非常了解 Java EE、Spring 等。类似这样的东西: BeanUtils.copyProperties(this, anotherBean); ?

标签: java spring spring-boot jpa merge


【解决方案1】:

Spring 的 BeanUtils.copyProperties(Source,Target) 成功了。谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2019-09-21
    • 2013-11-20
    相关资源
    最近更新 更多