Spring-boot添加Mybatis

在Spring-boot裏添加Mybatis須要添加mysql

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.1.1</version>
</dependency>

而後在配置類上添加MapperScan註解,自動掃描mapper接口spring

@MapperScan("package-info")sql

須要事務管理的話能夠添加 @EnableTransactionManagement 註解,spring自動會配置事務apache

 

而後必須手動配置 Mybatis 的 SqlSessionFactorytomcat

@Bean
	public SqlSessionFactory sqlSessionFactoryBean(DataSource ds) throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		// 設置數據源
		sqlSessionFactoryBean.setDataSource(ds);
		// 設置查找器
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		// 自動掃描mybatis文件
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
		return sqlSessionFactoryBean.getObject();
	}

Spring會自動注入DataSourcemybatis

而後在application.properties裏添加DataSource信息app

配置信息以下 : spring-boot

# DataSource
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# JDBC Pool
spring.datasource.poolName = hikariCP
spring.datasource.maximumPoolSize = 25
spring.datasource.minimumIdle = 3
spring.datasource.connectionTimeout = 30000
spring.datasource.idleTimeout = 30000
spring.datasource.pool-prepared-statements = true
spring.datasource.max-open-prepared-statements = 250

默認是用Tomcat 鏈接池 url

若是想使用HikariCP的話 在引用 spring-boot-starter-jdbc時排除tomcat-jdbc就行了spa

pom文件以下:

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-jdbc</artifactId>
		<exclusions>
			<exclusion>
				<!-- 取消引入tomcat jdbc -->
				<groupId>org.apache.tomcat</groupId>
				<artifactId>tomcat-jdbc</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
    <!--引入 HikariCP-->
	<dependency>
		    <groupId>com.zaxxer</groupId>
			<artifactId>HikariCP</artifactId>
	</dependency>
相關文章
相關標籤/搜索