Spring boot 配置 SqlSessionFactory
package cn.xt.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
/**
* SqlSession配置
*/
@Configuration
public class SqlSessionConfig {
private Logger logger = LoggerFactory.getLogger(SqlSessionConfig.class);
@Value("${spring.datasource.jndi-name}")
private String dataSourceJndiName;
@Value("${mybatis.mapper-locations}")
private String mapperLocations;
@Bean
public SqlSessionFactoryBean createSqlSessionFactory() {
SqlSessionFactoryBean sqlSessionFactoryBean = null;
try {
// 加载JNDI配置
Context context = new InitialContext();
DataSource dataSource = (DataSource)context.lookup(dataSourceJndiName);
// 实例SessionFactory
sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 配置数据源
sqlSessionFactoryBean.setDataSource(dataSource);
// 加载MyBatis配置文件
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
// 能加载多个,所以可以配置通配符(如:classpath*:mapper/**/*.xml)
sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources(mapperLocations));
// 配置mybatis的config文件(我目前用不上)
// sqlSessionFactoryBean.setConfigLocation("mybatis-config.xml");
} catch (Exception e) {
logger.error("创建SqlSession连接工厂错误:{}", e);
}
return sqlSessionFactoryBean;
}
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦