0
点赞
收藏
分享

微信扫一扫

spring4.30 mybaties和junit整合

SDKB英文 2022-04-30 阅读 71
javaspring

1.mybaties的整合

1.需要2个java类配置文件durildConfig和mybatiesConfig

每个类前需要添加@bean。
在java类配置文件springConfig不要忘了更新扫描包和peoper文件资源路径的更新

//springConfig
@Configuration
@ComponentScan({"student","mysql"})
@PropertySource("jdbc.properties.properties")

durildConfig负责配置数据库。

 @Bean
    public DataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/test");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("p1234");
        return druidDataSource;
    }

mybatiesConfig负责数据的映射工作

 @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //student是数据库中对应的对象所在的包
        sqlSessionFactoryBean.setTypeAliasesPackage("student");
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //mysql对应的是sql语句对应包
        mapperScannerConfigurer.setBasePackage("mysql");
        return mapperScannerConfigurer;
    }

2.创建类

需要创建2个类,2个接口
sql语句需要一个接口sql
基础对象需要一个类studentDao
studentService接口
studentServicelmp类
sql接口中负责书写sql语句

 @Select("select * from  user where id =#{id}")
    studentDao  select(Integer id);

    @Select("select * from user ")
    List<studentDao> selectAll();

studentDao负责基础对象的书写
studentServicelmp实现类

//不要忘记注解标记
@Service
public class studentServicelmp implements studentService {

    @Autowired
    private sql sql;
    @Override
    public studentDao findId(int id) {
        return sql.select(id);
    }

    @Override
    public List<studentDao> selectAll() {
        return sql.selectAll();
    }
}

studentService(还不太清楚)

studentDao findId(int id);

    List<studentDao> selectAll();

3.主程序的开发

public class mybaitesMain {
    public static void main(String[] args) {
        ApplicationContext ApplicationContext = new AnnotationConfigApplicationContext(springConfig.class);
        studentService bean = (studentService) ApplicationContext.getBean(studentService.class);
        studentDao id = bean.findId(2);
        for (studentDao studentDao : bean.selectAll()) {
            System.out.println(studentDao);
        }

        System.out.println(id);
    }
}
举报

相关推荐

0 条评论