免责声明:我仍然非常 MyBatis&春天请原谅我,如果下面缺少一些细节。
我有一些代码在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);
}
}
答案 0 :(得分:0)
您可以使用http://www.mybatis.org/spring/sqlsession.html
记录的SqlSessionTemplate
它将确保您获得与您正在使用的映射器相同的sqlsession。
如果对您的用例更有效,您也可以使用同一页面上记录的SqlSessionDaoSupport
。