How to get sqlSession instance in mybatis mapper proxy?

1.2k Views Asked by At

I have a mybatis mapper

public interface FooMapper {
    @Select("select now()")
    String getTime();
}

when debug I got below info

enter image description here

I want to get sqlSession instance. So I tried using reflection manner to get sqlSession.

    Field hField = fooMapper.getClass().getDeclaredField("h");

    MapperProxy mapperProxy = (MapperProxy) hField.get(fooMapper);

    Field sqlSessionField = mapperProxy.getClass().getDeclaredField("sqlSession");
    SqlSession sqlSession = (SqlSession) sqlSessionField.get(mapperProxy);  

but actually I got below error

java.lang.NoSuch FieldException: h
    at java.lang.Class.getDeclaredField(Class.java:2070)

So how to get sqlSession instance in fooMapper by reflection manner or other manner(if reflection is impossible)?

1

There are 1 best solutions below

1
A.Addepalle On

This works:

((MapperProxy)((Proxy)fooMapper).h).sqlSession

MapperProxy from org.apache.ibatis.binding

Proxy from Java.lang.reflect