2016-06-28 65 views
0

聲明:我仍然非常新到MyBatis &春天所以請原諒我,如果一些細節下面缺少。如何使用MapperFactoryBean獲取當前會話?

我有一些代碼在MyBatis中使用MapperFactoryBean來自動管理數據庫事務,而不必在我的Java代碼中創建DAO類。這也意味着當使用這種方法時,用戶不需要編寫任何會話特定的代碼,因爲MyBatis直接處理與數據庫本身進行通信的會話。

問題:所以當上述情況發生時,如果希望獲得當前會話,那麼您如何做到這一點?在Hibernate中,您可以執行getSessionFactory().getCurrentSession()以獲取當前會話。當MyBatis的MapperFactoryBean方法用於與數據庫通信時,MyBatis的等效命令是什麼?

這裏是我當前的代碼片段:

的beans.xml:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
    <property name="basePackage" value="com.countries.dataaccess" /> 
</bean> 

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
    <property name="dataSource" ref="dataSource" />  
</bean> 

<bean id="countriesMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
<property name="mapperInterface" value="com.countries.dataaccess.CountryMapper" /> 
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />   
</bean> 

<bean id="countriesFacade" class="com.countries.facade.CountriesFacade" /> 

com.countries.dataaccess.CountryMapper:

public interface CountryMapper { 

    public List<CountryOutlineDTO> getAllCountries(List<String> merchantType); 

    public CountryDetailsDTO getCountryInfo(String countryCode); 

    //etc .... 
} 

com.countries .delegate.CountriesServiceDelegate:

public interface CountriesServiceDelegate { 

    public CountryDetails getCountryDetails(String countryCode, String locale) throws Exception; 

    public List<CountryDetails> getAllCountryDetails(List<String> merchantTypeList, boolean verbose) throws Exception; 

    public Health getDBHealth(); 
} 

com.countries.delegate.impl.CountriesServiceDelegateImpl:

public class CountriesServiceDelegateImpl implements CountriesServiceDelegate { 

    @Autowired 
    private CountriesFacade countriesFacade; 

    @Override 
    public CountryDetails getCountryDetails(String countryCode, String locale) { 

    //Implementation logic here ... 

    } 

    @Override 
    public List<CountryDetails> getAllCountryDetails(List<String> merchantTypeList, boolean verbose) { 

    //Implementation logic here ... 

    } 
} 

com.countries.facade:

public class CountriesFacade { 

    @Autowired 
    @Qualifier("countriesMapper") 
    private CountryMapper countriesMapper; 

    public CountryDetails getCountryInfo(String countryCode, String locale) { 

    //Implementation logic here such as xyz = countriesMapper.getCountryInfo(countryCode); 

    } 

    public List<CountryDetails> getAllCountries(List<String> merchantType, boolean verbose) { 

    //Implementation logic here such as xyz = countriesMapper.getCountryInfo(countryCode); 

    } 
} 

回答