pom添加依赖
<!-- Mybatis集成 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>
方式一
application.yml中配置数据源与mapper文件路径
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
# 使用druid数据源,若不配置type会用默认的Tomcat数据源
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
mapper-locations: com/**/dao/*.xml
DAO接口贴上@Mapper注解,即可让Spring容器创建实例
方式二
在resources目录下新建datasource.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
通过配置类,配置Mybatis
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
@Configuration
@MapperScan(basePackages="com.**.dao")
@PropertySource("classpath:datasource.properties")
public class MybatisConfig {
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.url}")
private String url;
@Bean
public DataSource dataSource() throws Exception {
Properties prop = new Properties();
prop.put("driverClassName",driverClassName);
prop.put("username",username);
prop.put("password",password);
prop.put("url",url);
return DruidDataSourceFactory.createDataSource(prop);
}
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource)
throws IOException {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
ResourcePatternResolver res = new PathMatchingResourcePatternResolver();
sqlSessionFactory.setMapperLocations(
res.getResources("classpath:com/**/dao/*.xml"));
return sqlSessionFactory;
}
}
网友评论