在Spring-boot里添加Mybatis需要添加
org.mybatis.spring.boot mybatis-spring-boot-starter 1.1.1
然后在配置类上添加MapperScan注解,自动扫描mapper接口
@MapperScan("package-info")
需要事务管理的话可以添加 @EnableTransactionManagement 注解,spring自动会配置事务
然后必须手动配置 Mybatis 的 SqlSessionFactory
@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会自动注入DataSource
然后在application.properties里添加DataSource信息
配置信息如下 :
# DataSourcespring.datasource.url = jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNullspring.datasource.username = rootspring.datasource.password = rootspring.datasource.driverClassName = com.mysql.jdbc.Driver# JDBC Poolspring.datasource.poolName = hikariCPspring.datasource.maximumPoolSize = 25spring.datasource.minimumIdle = 3spring.datasource.connectionTimeout = 30000spring.datasource.idleTimeout = 30000spring.datasource.pool-prepared-statements = truespring.datasource.max-open-prepared-statements = 250
默认是用Tomcat 连接池
如果想使用HikariCP的话 在引用 spring-boot-starter-jdbc时排除tomcat-jdbc就好了
pom文件如下:
org.springframework.boot spring-boot-starter-jdbc org.apache.tomcat tomcat-jdbc com.zaxxer HikariCP