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实现类文章来源:https://www.toymoban.com/news/detail-426010.html
//不要忘记注解标记
@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(还不太清楚)文章来源地址https://www.toymoban.com/news/detail-426010.html
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);
}
}
到了这里,关于spring4.30 mybaties和junit整合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!