-
导入坐标,MyBatis坐标不能少,Spring整合MyBatis还有自己专用的坐标,此外Spring进行数据库操作的jdbc坐标是必须的,剩下还有mysql驱动坐标,本例中使用了Druid数据源,这个倒是可以不要
<dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.16</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--1.导入mybatis与spring整合的jar包--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!--导入spring操作数据库必选的包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.10.RELEASE</version> </dependency> </dependencies>
-
Spring核心配置
@Configuration @ComponentScan("com.itheima") @PropertySource("jdbc.properties") public class SpringConfig { }
-
MyBatis要交给Spring接管的bean
//定义mybatis专用的配置类 @Configuration public class MyBatisConfig { // 定义创建SqlSessionFactory对应的bean @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){ //SqlSessionFactoryBean是由mybatis-spring包提供的,专用于整合用的对象 SqlSessionFactoryBean sfb = new SqlSessionFactoryBean(); //设置数据源替代原始配置中的environments的配置 sfb.setDataSource(dataSource); //设置类型别名替代原始配置中的typeAliases的配置 sfb.setTypeAliasesPackage("com.itheima.domain"); return sfb; } // 定义加载所有的映射配置 @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer msc = new MapperScannerConfigurer(); msc.setBasePackage("com.itheima.dao"); return msc; } }
-
数据源对应的bean,此处使用Druid数据源
@Configuration public class JdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String userName; @Value("${jdbc.password}") private String password; @Bean("dataSource") public DataSource dataSource(){ DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(userName); ds.setPassword(password); return ds; } }
-
数据库连接信息(properties格式)
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false jdbc.username=root jdbc.password=root