栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring4.30 mybaties和junit整合

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring4.30 mybaties和junit整合

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 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 selectAll() {
        return sql.selectAll();
    }
}

studentService(还不太清楚)

studentDao findId(int id);

    List 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);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/848209.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号