简体   繁体   中英

How do I refactor hibernate entities?

My use case is as follows: I've inherited a project that is using hibernate. The entity I'm focused on right now is, for the purposes of this exercise, closed to modification . The object of the exercise is to replace the use of the legacy entity with an unrelated implementation that is better suited to the new requirements.

The goal is to be able to move functionality from the old entity to the new incrementally .

As is, the use of the legacy entity looks something like

    //...

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

With configuration magic hidden off in some hbm.xml file

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

How do I arrange analogous code for a new entity mapped to the same table

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

without breaking the code paths that are still using LegacyEntity in the same process?

"The entity I'm focused on right now is, for the purposes of this exercise, closed to modification. ... The goal is to be able to move functionality from the old entity to the new incrementally." I find this contradictory. When replacing a class by another, I have always had success by: 1) incrementally changing the old class API to be a subset of the new class API, 2) renaming the old type to have the same name and package as the new class, 3) removing the old class (that we renamed in step 2). While doing all of this, I rely as much as possible on the refactoring capabilities of the IDE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM