SpingBoot整合Mybatis配置
2019-02-15 本文已影响0人
大黄想去看极光
1.添加Pom依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
2.新建DataSource配置类,不要忘了扫描包
@Configuration
@MapperScan("com.logoxiang.mapper")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${jdbc.password}")
private String jdbcPassword;
@Bean(name = "dataSource")
public DruidDataSource createDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(jdbcDriver);
dataSource.setUrl(jdbcUrl);
dataSource.setUsername(jdbcUsername);
dataSource.setPassword(jdbcPassword);
return dataSource;
}
}
3.新建SessionFactory配置类
@Configuration
public class SessionFactoryConfiguration {
// mybatis-config.xml配置文件的路径
private static String mybatisConfigFile;
@Value("${mybatis_config_file}")
public void setMybatisConfigFile(String mybatisConfigFile) {
SessionFactoryConfiguration.mybatisConfigFile = mybatisConfigFile;
}
// mybatis mapper文件所在路径
private static String mapperPath;
@Value("${mapper_path}")
public void setMapperPath(String mapperPath) {
SessionFactoryConfiguration.mapperPath = mapperPath;
}
// 实体类所在的package
@Value("${type_alias_package}")
private String typeAliasPackage;
@Qualifier("dataSource")
@Autowired
private DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 设置mybatis configuration 扫描路径
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFile));
// 添加mapper 扫描路径
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
// 设置dataSource
sqlSessionFactoryBean.setDataSource(dataSource);
// 设置typeAlias 包扫描路径
sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage);
return sqlSessionFactoryBean;
}
}
如果@Autowired报错,则在settings里面修改警报级别为warning
QQ截图20190215210213.png
4.别忘了在配置文件中添加数据
#DataSource
#数据库驱动
jdbc.driver=com.mysql.jdbc.Driver
#数据库链接
jdbc.url=jdbc:mysql://localhost:3306/pinyougoudb?serverTimezone=GMT%2B8
#数据库用户名
jdbc.username=root
#数据库密码
jdbc.password=2237
#Mybatis
mybatis_config_file=SqlMapConfig.xml
mapper_path=/mapper/**.xml
type_alias_package=com.logoxiang.pojo
5.如果需要mybatis配置文件,则在resources添加上
QQ截图20190215212233.png