mybatis關聯映射一對多

實際項目中也存在不少的一對多的狀況,下面看看這個簡單的例子

table.sqljava

CREATE TABLE tb_clazz(
id INT PRIMARY KEY AUTO_INCREMENT,
CODE VARCHAR(18),
NAME VARCHAR(18)
);

INSERT INTO tb_clazz(CODE,NAME) VALUES('w5','五年級');

CREATE TABLE tb_student(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(18),
sex VARCHAR(18),
age INT,
clazz_id INT,
FOREIGN KEY (clazz_id) REFERENCES tb_clazz(id)
);

INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('張三','男',13,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('李四','女',14,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('王五','男',13,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('趙六','女',12,1);

建立一個Clazz對象和一個Student對象分別映射tb_clazz和tb_student表。班級和學生是一對多的關係,即一個班級能夠有不少個學生,在Clazz類定義了一個student屬性,該屬性是一個List集合,用來映射一對多的關聯關係,表示一個班級有多個學生
學生和班級是多對一的關係,即一個學生只屬於一個班級,在student類當中定義一個clazz屬性,該屬性是一個Clazz類型,用來映射 多對一的關聯關係,表示該學生所屬的班級
Clazz.javamysql

public class Clazz implements Serializable {

    private Integer id; // 班級id,主鍵
    private String code; // 班級編號
    private String name; // 班級名稱

    // 班級和學生是一對多的關係,即一個班級能夠有多個學生
    private List<Student> students;
}

Student.javasql

public class Student implements Serializable {
    private Integer id; // 學生id,主鍵
    private String name; // 姓名
    private String sex;  // 性別
    private Integer age; // 年齡

    // 學生和班級是多對一的關係,即一個學生只屬於一個班級
    private Clazz clazz;
}

xml文件的配置
ClazzMapper.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">
<!-- namespace指用戶自定義的命名空間。 -->
<mapper namespace="com.rookie.bigdata.mapper.ClazzMapper">

    <!-- 根據id查詢班級信息,返回resultMap -->
      <select id="selectClazzById" parameterType="int" resultMap="clazzResultMap">
        SELECT * FROM tb_clazz  WHERE id = #{id}
      </select>
      
       <!-- 映射Clazz對象的resultMap -->
    <resultMap type="com.rookie.bigdata.domain.Clazz" id="clazzResultMap">
        <id property="id" column="id"/>
        <result property="code" column="code"/>
        <result property="name" column="name"/>
        <!-- 一對多關聯映射:collection fetchType="lazy"表示懶加載  -->
        <collection property="students" javaType="ArrayList"
      column="id" ofType="com.rookie.bigdata.domain.Student"
      select="com.rookie.bigdata.mapper.StudentMapper.selectStudentByClazzId"
      fetchType="lazy">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="sex" column="sex"/>
        <result property="age" column="age"/>
      </collection>
    </resultMap>
    
    
  

</mapper>

StudentMapper.xmlsession

<?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">
<!-- namespace指用戶自定義的命名空間。 -->
<mapper namespace="com.rookie.bigdata.mapper.StudentMapper">

    <!-- 根據id查詢學生信息,多表鏈接,返回resultMap -->
  <select id="selectStudentById" parameterType="int" resultMap="studentResultMap">
    SELECT * FROM tb_clazz c,tb_student s
    WHERE c.id = s.clazz_id
     AND s.id = #{id}
  </select>
  
  <!-- 根據班級id查詢學生信息,返回resultMap -->
  <select id="selectStudentByClazzId" parameterType="int" 
  resultMap="studentResultMap">
    SELECT * FROM tb_student WHERE clazz_id = #{id}
  </select>
  
   <!-- 映射Student對象的resultMap -->
    <resultMap type="com.rookie.bigdata.domain.Student" id="studentResultMap">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="sex" column="sex"/>
        <result property="age" column="age"/>
        <!-- 多對一關聯映射:association   -->
        <association property="clazz" javaType="com.rookie.bigdata.domain.Clazz">
            <id property="id" column="id"/>
            <result property="code" column="code"/>
            <result property="name" column="name"/>
        </association>
    </resultMap>

</mapper>

mybatis-config.xmlmybatis

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
  <!--  XML 配置文件包含對 MyBatis 系統的核心設置 -->
<configuration>
    <!-- 指定 MyBatis 所用日誌的具體實現 -->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
        <!-- 要使延遲加載生效必須配置下面兩個屬性 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <environments default="mysql">
    <!-- 環境配置,即鏈接的數據庫。 -->
    <environment id="mysql">
    <!--  指定事務管理類型,type="JDBC"指直接簡單使用了JDBC的提交和回滾設置 -->
      <transactionManager type="JDBC"/>
      <!--  dataSource指數據源配置,POOLED是JDBC鏈接對象的數據源鏈接池的實現。 -->
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.47.151:3306/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  <!-- mappers告訴了MyBatis去哪裏找持久化類的映射文件 -->
  <mappers>
    <mapper resource="mapper/ClazzMapper.xml"/>
    <mapper resource="mapper/StudentMapper.xml"/>
  </mappers>
</configuration>

ClazzMapp.javaapp

public interface ClazzMapper {

    // 根據id查詢班級信息
    Clazz selectClazzById(Integer id);
    
}

StudentMapper.javadom

public interface StudentMapper {

    // 根據id查詢學生信息
    Student selectStudentById(Integer id);
    
}

測試代碼
OneToManyTest.java測試

public class OneToManyTest {

    public static void main(String[] args) throws Exception {
        // 讀取mybatis-config.xml文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 初始化mybatis,建立SqlSessionFactory類的實例
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);
        // 建立Session實例
        SqlSession session = sqlSessionFactory.openSession();
        
        OneToManyTest t = new OneToManyTest();
        
        t.testSelectClazzById(session);
//      t.testSelectStudentById(session);
        
        // 提交事務
        session.commit();
        // 關閉Session
        session.close();
    }
    
    // 測試一對多,查詢班級Clazz(一)的時候級聯查詢學生Student(多)  
    public void testSelectClazzById(SqlSession session){
        // 得到ClazzMapper接口的代理對象
        ClazzMapper cm = session.getMapper(ClazzMapper.class);
        // 調用selectClazzById方法
        Clazz clazz = cm.selectClazzById(1);
        System.out.println(clazz);
        // 查看查詢到的clazz對象信息
        System.out.println(clazz.getId() + " "+ clazz.getCode() + " "+clazz.getName());
        // 查看clazz對象關聯的學生信息
        List<Student> students = clazz.getStudents();
        for(Student stu : students){
            System.out.println(stu);
        }
    }
    
    // 測試多對一,查詢學生Student(多)的時候級聯查詢 班級Clazz(一)
    public void testSelectStudentById(SqlSession session){
        // 得到StudentMapper接口的代理對象
        StudentMapper sm = session.getMapper(StudentMapper.class);
        // 調用selectStudentById方法
        Student stu = sm.selectStudentById(1);
        // 查看查詢到的Student對象信息
        System.out.println(stu);
        // 查看Student對象關聯的班級信息
        System.out.println(stu.getClazz());
    }

}

至此一對多關係關係映射測試完成fetch

相關文章
相關標籤/搜索