Is all code run inside an mvc controller method in the same session?

55 Views Asked by At

I have the following model:

many to many between entity Foo and Bar. Foo has a LinkedHashSet of Bar annotated with @OrderBy.

Controller includes a method that first saves a new Bar to the set, and then gets all Bar from one Foo.

Set<Bar> methodName(FooId fid, Bar b){
    fooService.addBar(fid, b);
    return fooService.getBarsOfFoo(fid);
}

service methods:

@Transactional
void addBar(UUID fid, Bar b){
    Foo f = fooRepository.getFoo(fid);
    f.getBars().add(b);
}

@Transactional(readOnly = true)
Set<Bar> getBarsOfFoo(UUID fid){
    return fooRepository.getFoo(fid).getBars();
}

the issue is that when calling the method, all Bars are ordered except the last introduced one. I think it has something to do with hibernate first-level caching, but I am not sure when the session associated with that method starts or ends.

Are both session methods from that controller method run within the same session?

1

There are 1 best solutions below

0
On

A Hibernate session is not the same as an MVC controller session from the official documentation https://developer.jboss.org/wiki/SessionsAndTransactions

it depends on your configuration and who and how you're creating this session

but in principle, there are 3 patterns

session-per-request

the session-per-request implementation pattern. A single Session and a single database transaction implement the processing of a particular request event (for example, a Http request in a web application). Do never use the session-per-operation anti-pattern! (There are extremely rare exceptions when session-per-operation might be appropriate, you will not encounter these if you are just learning Hibernate.)

session-per-request-with-detached-objects

Once persistent objects are considered detached during user think-time and have to be reattached to a new Session after they have been modified.

session-per-conversation

In this case a single Session has a bigger scope than a single database transaction and it might span several database transactions. Each request event is processed in a single database transaction, but flushing of the Session would be delayed until the end of the conversation and the last database transaction, to make the conversation atomic. The Session is held in disconnected state, with no open database connection, during user think-time. Hibernate's automatic optimistic concurrency control (with versioning) is used to provide conversation isolation.

So viewing the documentation you probably using session-per-conversation so might to need to flush your session before your next call.