views:

1782

answers:

1

I'm trying to make an application that keeps an object model in sync with a database by observing all changes and then immediately persisting the objects in questions. Many of the object in the model have children in large lists or trees.

When I load an object from the database, I rely on a one-way cascading relationship to also retrieve all of its children and include them in the application.

However, it is possible to alter a field in the parent object which requires persistence and I can determine that none of the children are affected. So I would like to persist the parent, without hitting the database with all the cascaded child persists.

eg

@Entity
public class Parent {

    @OneToMany(cascade=CascadeType.ALL)
    public List children;

}

How can I override the cascade option when I persist a Parent object? Or should I just set it to REFRESH and make sure I never need a cascading persist?

+2  A: 

Reading the objects from the database and persisting them rely upon two different annotations.

When you load an object, it will also get the other end of any eager (FetchType.EAGER) relationships, as defined by the fetch property on the relationship.

Depending on your JPA provider, you may have options to override this behaviour. EclipseLink, via the incredibly useful QueryHint.BATCH, certainly does.

When you persist, delete or refresh, the cascade type is what's relevant.

So, lose the cascade, keep the fetch and problem solved.

Personally I think cascade all is asking for trouble but opinions will vary.

A decent JPA provider will have a pretty sophisticated (configurable) caching scheme already. Perhaps you should be asking why you're reinventing that particular wheel?

Is it an issue of asynchronous updates purely for performance? Or is something else the reason?

cletus
It's a standalone app with the database on the same machine or a nearby server. The entire model is required to be in memory so the user can play with it. I'm trying to have the result of all user actions persisted so they never have to click "save".
Cogsy