Question

I'm using Hibernate 4 and am implementing my DAOs and Services. It seems that I could just implement saveOrUpdate() instead of implement save() and update() separately, which would require the services to check whether save() or update() should be called.

1) Are Hibernate's unsaved-value checks in saveOrUpdate() optimized enough to call it always or should I do the check myself?

2) Is saveOrUpdate() unusable if the decision to save or update depends on a field other than the key?

Was it helpful?

Solution

1) See here: Hibernate automatic state detection it says

saveOrUpdate() does the following:

-if the object is already persistent in this session, do nothing

-if another object associated with the session has the same identifier, throw an exception

-if the object has no identifier property, save() it

-if the object's identifier has the value assigned to a newly instantiated object, save() it

-if the object is versioned by a or , and the version property value is the same value assigned to a newly instantiated object, save() it

-otherwise update() the object

So in some cases an occasional Select is performed to see if an object is already existing (if the ID is not some auto generated value for example). So if you do it manually or if you let hibernate do it makes no difference for me, if any I would say using saveOrUpdate has better performance since firstly more checks are performed to out-rule an update, this can save time for some inserts and secondly when doing checks on your own you have to go through more layers with full hibernate select when checking. Also: doing checks yourself will have an impact on code maintainability. For instance if you add second level caching you might need to optimize your save and selects. Or If you apply some other tweaks, you might be in a position where you need to change code at many more places.

2) saveOrUpdate only considers the entry identifier. So yes it is unusable for fields other than the key.

OTHER TIPS

saveOrUpdate() checks if entity already have ID. If true calls update(), otherwise - save() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top