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

MyBatis使用级联操作解决lombok构造方法识别失败问题

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

MyBatis使用级联操作解决lombok构造方法识别失败问题

先解决一下idea无法识别lombok构造方法的问题,解决方案是在idea的插件中下载并安装lombok插件。

MyBatis级联操作,列举最简单的student-classes(学生与班级)的关系表:

create table if not exists student (
  id int primary key auto_increment,
  name varchar(20) not null comment '学生姓名',
  cid int not null comment '班级id'
);
create table if not exists classes (
  id int primary key auto_increment,
  name varchar(20) not null comment '班级名'
);

接下来,创建关系表对应的实体类:

@Data
public class Student {
  private long id;
  private String name;
  private Classes classes;
}
@Data
public class Classes {
  private long id;
  private String name;
  private List students;
}

在repository包下新建StudentRepository接口:

public interface StudentRepository {
  public Student findById(long id);
}

然后创建对应的mapper文件StudentRepository.xml:






  
  
    
    
    
      
      
    
  
  
  
    select s.id,s.name,c.id as cid,c.name as cname from student s,classes c where s.id = #{id} and s.cid = c.id
  

注意这里有几个限制:

1.命名空间,xml文件的namespace必须是对应接口的全类名

2.Statement标签的id必须与接口方法相同,其中parameterType为参数,resultType为返回类型,复杂类型用resultMap

3.复杂类型resultMap中多对一用association,一堆多用集合collection

MyBatis执行sql返回的结果集会和关系对象映射起来,注意列与字段的对应关系。

然后将mapper引入:


  

编写测试方法:

@Test
public void test03() {
  InputStream inputStream = AppTest.class.getClassLoader().getResourceAsStream("config.xml");
  SqlSessionFactory sqlSessionFactory = (new SqlSessionFactoryBuilder()).build(inputStream);
  try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
    // 级联查询
    StudentRepository studentRepository = sqlSession.getMapper(StudentRepository.class);
    System.out.println(studentRepository.findById(1L));
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/133335.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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