JavaWeb04-MyBatis与Spring结合
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
@Configuration
@MapperScan(basePackages = "com.example.mapper") // 指定Mapper接口所在包
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource()); // 设置数据源
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml")); // 设置MyBatis Mapper XML文件位置
return sqlSessionFactoryBean.getObject();
}
// 数据源配置、其他Spring配置...
}
这段代码展示了如何在Spring项目中配置MyBatis的SqlSessionFactory。通过@MapperScan
注解指定了Mapper接口所在的包,sqlSessionFactory()
方法配置了数据源和MyBatis的Mapper XML文件位置。这是一个典型的Spring和MyBatis整合的配置类示例。
评论已关闭