vladmihalcea / hypersistence-optimizer

Hypersistence Optimizer allows you to get the most out of JPA and Hibernate. By scanning your application configuration and mappings, Hypersistence Optimizer can tell you what changes you need to do to speed up your data access layer.
https://vladmihalcea.com/hypersistence-optimizer/
Apache License 2.0
306 stars 43 forks source link

(How to) retrieve the original Connection from a SessionDelegator? #184

Closed hannibal218bc closed 1 year ago

hannibal218bc commented 1 year ago

Hi,

some places in the application I'm analyzing retrieve the java.sql.Connection from a Session like this:

        if (hibSession instanceof SessionImpl){
            return ((SessionImpl) hibSession).connection();
        }
        if (hibSession instanceof StatelessSessionImpl){
            return ((StatelessSessionImpl) hibSession).connection();
        }

When using the optimizer, the session objects are of type SessionDelegator and the above code doesn't work. However, the type already has a public Session getOriginalSession() method, so I'd like to do something like this:

        if (hibSession instanceof SessionDelegator) {
            return getConnectionFromSession(((SessionDelegator) hibSession).getOriginalSession());
        }

However, SessionDelegator is not visible... would it be possible to add a common supertype for the various delegators, and the public getOriginalSession() declaration there? Or is there a better way to achieve this...?

Thank you!

vladmihalcea commented 1 year ago

You can use the doReturningWork method against the Session, and it will work the same even if the SessionDelegator is used:

Connection connection = session.doReturningWork(c -> c);

hannibal218bc commented 1 year ago

Thanks!

vladmihalcea commented 1 year ago

You're welcome.