spring整合mybatis学习笔记

spring整合mybatis

1、方法一(注解配置)

1.1配置springconfig类

@Configuration    //标注为配置类
@ComponentScan("com.frt") //开启注解扫描
@PropertySource("Jdbc.properties") //导入properties文件
@Import({JdbcConfig.class, MybatisConfig.class}) //引入其他配置类
public class SpringConfig {
}

1.2配置JdbcConfig类

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;
//给常规数据类型赋值用@value()注解
    @Bean //将此方法返回值放入ICO容器中
    public DataSource dataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

1.3配置mybatiscongfig类

public class MybatisConfig {

    @Bean //创建sqlsessionFactoryBean放入IOC容器
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setTypeAliasesPackage("com.frt.bean");
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean //创建实现类代理对象
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer=new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.frt.dao");
        return mapperScannerConfigurer;
    }
}

你可能感兴趣的:(mybatis,spring,学习)