SpringBoot整合MyBatis【數據庫連接】
阿新 • • 發佈:2019-04-13
.config imp group ram -c java val 數據源 cati
1、pom文件引入
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- 測試 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!-- mysql 依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- springboot-web組件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
2、application.properties配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3、配置sqlsessionFactiontory;
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;
}
}
4、創建對應的Mapper層service層就可以直接連接使用了!
SpringBoot整合MyBatis【數據庫連接】