[hibernate-dev] Using hibernate/spring for batch jobs - open session in view pattern?

Sanne Grinovero sanne at hibernate.org
Wed Mar 30 18:42:19 EDT 2011


2011/3/30  <orly at notrly.com>:
> so i think i understand the open session in view pattern when generally
> used with controllers and creating a filter which creates the hibernate
> session and starts the transaction and then there are multiple service
> calls for that http request.

Actually I wouldn't like it to work with a framework which controls
transaction boundaries, especially if it mandates a 1:1 relation with
http requests.

>
> im trying to do the same thing for batch jobs but running into some issues.
>
> so i have a set of batch jobs, and for each one, it calls a service to get
> a list of objects. it does this in the batch class. then for each object,
> it will make a service call to process the object. i have this call in the
> batch class wrapped in a try catch, so if an exception occurs, i log it,
> but iw ant the next object to be processed and persisted.
>
> i was creating a hibernate session in this batch class and binding it to
> the current thread - this was so that the session used to get the list of
> objects is the same session used to process each object since in the
> services it might call object.getList which is lazy loaded (can only be
> loaded from that same session). but im not creating a transaction in that
> batch class either because these batch jobs can run long, and if the db
> timeout is at 5 min i'll get an error saying the db connection closed for
> this outer transaction (since each service call will have an inner
> transaction)
>
> but there was a problem w/ this when say the first object in the list
> threw an exception in the service, then when i process the 2nd object and
> try to access something from the obj that's lazy loaded, it will say
> there's no session. this seems to be because im not actually supposed to
> reuse a session after an exception occurs since hibernate does something
> to it..?

Yes, that's explained on the manual: if an exception happens, you have
to close the Session and open a new one.

Generally speaking, and assuming you use a connection pool, opening
and closing a Session is a cheap operation, don't be afraid to hurt
performance avoiding to close it when it makes sense.
Especially on batch jobs you'd like to open one for each and close it
as soon as possible, or use clear() after each independent job.

>
> any ideas on how to resolve this?
>
> whats the best way to go about doing something like this? it seems like
> something that's really common for batch jobs - getting a list of objects,
> and process each one independently of the other (persisting it and if
> exception occurs, doesnt affect persisting of the others).
>
> thanks

Please make this kind of questions on the user forum:
https://forum.hibernate.org/index.php

Regards,
Sanne



More information about the hibernate-dev mailing list