mybatis | 您所在的位置:网站首页 › keil4没有atmel › mybatis |
数据库表的关系无非就四种:1、一对多(多对一),2、一对一,3、多对多,4、没有关系。其实面对数据表的多对多关系并没有那么复杂,那要看你怎么实现,传统的方法无非就是查询sql语句,而我要的是不通过自己写sql语句来达到查询出数据。这个我貌似不会,在网上找了太多资料,结果太让我失望了,不是要xml文件就是注解写sql,多对多的关系处理不清。想了好久,也碰到好多壁障,不过还是做出来了。 功能:通过中间表查询出与之关联的表的个别字段数据 传统方法(注解编写sql语句的方式) 表关系(歌单表、歌曲表、歌曲集合表(中间表)) 一个歌单可以有多首歌曲,一首歌曲可以有多个歌单。 这是歌曲表:![]() ![]() ![]() 无sql语句查询就比较简单(我是说操作步骤)。要完成接下来的操作要导入mybatis-plus的依赖(因为我本来用的就是mybatis-plus)要导入依赖请跳往mybatis-plus官网 然后利用mybatis-plus service层继承IService public interface ListSongService extends IService { } 直接测试-测试类 @Autowired ListSongService listSongService; @Autowired SongService songService; @Test void test02() { //创建一个map容器 Map columnMap=new HashMap(); //给map容器中放值 columnMap.put("song_list_id",1); //调用IService类中的方法listByMap(解析在下面) //查询出中间表的数据 List gg = listSongService.listByMap(columnMap); //创建一个list集合,集合的类型是:Integer Listsongids=new ArrayList(); for (int i=0; i Map kk=new HashMap(); //给map放值 kk.put("id",gg.get(i).getId()); kk.put("name",nn.get(i).getName()); //给集合放值 hh.add(kk); } //输出 System.out.println(hh); } //IService类listByMap方法解析: //在创建一个map容器后给容器赋值:columnMap.put("song_list_id",1),前面song_list_id是数据库字段名,后面的1是字段名的值。具体使用方法可去mybatis-plus官网查询 //IService类listByIds方法解析:是根据主键id的集合批量查询数据 // 测试-controller @GetMapping("/selectListsong") public List selectListsong(@RequestParam("id") Integer id){ //根据表字段查询数据 Map columnMap=new HashMap(); columnMap.put("song_list_id",id); List gg = listSongService.listByMap(columnMap); //创建一个集合,通过for循环取出ListSong表中歌曲的id Listsongids=new ArrayList(); for (int i=0; i Map kk=new HashMap(); kk.put("id",gg.get(i).getId()); kk.put("name",nn.get(i).getName()); hh.add(kk); } return hh; } //注解我就不写了,跟测试类的一样 |
CopyRight 2018-2019 实验室设备网 版权所有 |