SSM整合以及相关补充( 三 )

  1. jdbc配置资文档准备
// jdbc.propertiesjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/ssmjdbc.username=rootjdbc.password=123456
  1. SpringConfig配置类
// SpringConfigpackage com.itheima.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;import org.springframework.context.annotation.PropertySource;import org.springframework.transaction.annotation.EnableTransactionManagement;// Spring配置类@Configuration// 扫描包@ComponentScan({"com.itheima.service"})// 资源载入@PropertySource("classpath:jdbc.properties")// 与MyBatis链接@Import({JdbcConfig.class,MyBatisConfig.class})// 开启事务平台@EnableTransactionManagementpublic class SpringConfig {}
  1. MyBatisConfig配置类
// JdbcConfigpackage com.itheima.config;import com.alibaba.druid.pool.DruidDataSource;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.PlatformTransactionManager;import javax.sql.DataSource;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    // 配置资源(这里采用的是DruidDataSource)    @Bean    public DataSource dataSource(){        DruidDataSource dataSource = new DruidDataSource();        dataSource.setDriverClassName(driver);        dataSource.setUrl(url);        dataSource.setUsername(username);        dataSource.setPassword(password);        return dataSource;    }    // 设置为Bean    // 配置事务平台(这里采用的是DataSourceTransactionManager)    @Bean    public PlatformTransactionManager transactionManager(DataSource dataSource){        DataSourceTransactionManager ds = new DataSourceTransactionManager();        ds.setDataSource(dataSource);        return ds;    }}// MyBatisConfigpackage com.itheima.config;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.mapper.MapperScannerConfigurer;import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MyBatisConfig {    // 设置为Bean    // 创建工厂SqlSessionFactory,用于实现数据库交互    @Bean    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();        factoryBean.setDataSource(dataSource);        factoryBean.setTypeAliasesPackage("com.itheima.domain");        return factoryBean;    }    // 设置为Bean    // 创建映射,并定义映射地址,采用MapperScannerConfigurer    @Bean    public MapperScannerConfigurer mapperScannerConfigurer(){        MapperScannerConfigurer msc = new MapperScannerConfigurer();        msc.setBasePackage("com.itheima.dao");        return msc;    }}

经验总结扩展阅读