【问题标题】:How do I refactor hibernate entities?如何重构休眠实体?
【发布时间】:2017-12-29 17:52:24
【问题描述】:

我的用例如下:我继承了一个使用休眠的项目。就本练习而言,我现在关注的实体不允许修改。练习的目的是用更适合新需求的不相关实现替换旧实体的使用。

目标是能够将功能从旧实体增量移动到新实体。

按原样,遗留实体的使用看起来像

    //...

    final Session currentSession = sessionFactory().getCurrentSession();
    {
        LegacyEntity oldAndBusted = get(currentSession, "12345");

        oldAndBusted.change(...);

        put(oldAndBusted);  
    }
}   

LegacyEntity get(final Session currentSession, String businessId) {
    return (LegacyEntity) currentSession        
        .createQuery("from PurpleMonkeyDishwasher where businessId = ?")
        .setParameter(0, "12345")
        .uniqueResult();
}

void put(final Session currentSession, LegacyEntity changed) {
    currentSession.saveOrUpdate(changed);
}

在一些 hbm.xml 文件中隐藏了配置魔法

<class name="LegacyEntity" table="PurpleMonkeyDiswasher">
    <!-- stuff -->
</class>

如何为映射到同一张表的新实体安排类似代码

BuzzwordCompliantEntity get(final Session currentSession, String businessId);
void put(BuzzwordCompliantEntity changed);

不破坏在同一进程中仍在使用 LegacyEntity 的代码路径?

【问题讨论】:

  • 在迁移时非常非常小心。

标签: java hibernate refactoring


【解决方案1】:

“就本练习而言,我现在关注的实体是不允许修改的。......目标是能够将功能从旧实体逐步迁移到新实体。”我觉得这很矛盾。当用另一个类替换一个类时,我总是通过以下方式取得成功:1)逐渐将旧类 API 更改为新类 API 的子集,2)将旧类型重命名为与新类具有相同的名称和包, 3)删除旧类(我们在步骤 2 中重命名)。在做这一切的同时,我尽可能地依赖 IDE 的重构功能。

【讨论】:

    猜你喜欢
    • 2017-12-13
    • 2015-10-31
    • 2019-10-27
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    相关资源
    最近更新 更多