1. 程式人生 > 程式設計 >MyBatis使用級聯操作解決lombok構造方法識別失敗問題

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<Student> students;
}

在repository包下新建StudentRepository介面:

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

然後建立對應的mapper檔案StudentRepository.xml:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.wts.repository.StudentRepository">
  
  <resultMap id="studentMap" type="com.wts.entity.Student">
    <id column="id" property="id"></id>
    <result column="name" property="name"></result>
    <association property="classes" javaType="com.wts.entity.Classes">
      <id column="cid" property="id"></id>
      <result column="cname" property="name"></result>
    </association>
  </resultMap>
  
  <select id="findById" parameterType="long" resultMap="studentMap">
    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
  </select>
</mapper>

注意這裡有幾個限制:

1.名稱空間,xml檔案的namespace必須是對應介面的全類名

2.Statement標籤的id必須與介面方法相同,其中parameterType為引數,resultType為返回型別,複雜型別用resultMap

3.複雜型別resultMap中多對一用association,一堆多用集合collection

MyBatis執行sql返回的結果集會和關係物件對映起來,注意列與欄位的對應關係。

然後將mapper引入:

<mappers>
  <mapper resource="com/wts/repository/StudentRepository.xml"></mapper>
</mappers>

編寫測試方法:

@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));
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。