Reputation: 83
I have been executing stored procedure using Callable statement from datasource. Now this procedure has to read data from an insert query executed just before SP execution in same service. so this creates a problem as the whole service is wrapped around a @Transactional annotation and commit is only done after service completes. So , is there any way to get the current session of current @Transactional annotation . getCurrentSession of SessionFactory is giving me a differrent session.
Upvotes: 5
Views: 9669
Reputation: 2749
I believe your understanding is correct. In @Transactional context, if you call getCurrentSession() method, it creates new Session object if it does not exist or returns Session which is attached to current transaction. OpenSession() method always creates new session. @Transactional helps you to extend scope of Session.
You can get current session inside the method (with @Transactional annotation ), by calling following method. And of course if you want to retrieve data , it depends in ISOLATION LEVEL.
sessionFactory.getCurrentSession()
Session is open first time when getCurrentSession() is executed and it is closed when transaction ends and it is flushed before transaction commits.
in non-transactional context, if we call getCurrentSession() we get an exception . And by default propagation is Required, make sure you dont have other propagation types.
And with following annotation in your configuration class, it enables it
@EnableTransactionManagement
Upvotes: 3
Reputation: 2279
If you using sessionfactory you can get by this code
@Autowired
private SessionFactory sessionFactory;
public Session getSession() {
try {
return sessionFactory.getCurrentSession();
} catch (Exception e) {
System.out.println(e.getMessage().toString());
}
return sessionFactory.openSession();
}
Upvotes: 0