MyBatis一对多关联映射

ClazzMapper.java

package mapper;

import pojo.Clazz;


public interface ClazzMapper {

   Clazz selectClazzById(Integer id);
    // 根据id查询班级信息
   
}

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="mapper.ClazzMapper">

   <!-- 根据id查询班级信息,返回resultMap -->
    <select id="selectClazzById" parameterType="int" resultMap="clazzResultMap">
      SELECT * FROM tb_clazz  WHERE id = #{id}
    </select>
     
    <!-- 映射Clazz对象的resultMap -->
   <resultMap type="pojo.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="pojo.Student"
           select="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.java

package mapper;

import pojo.Student;


public interface StudentMapper {

   Student selectStudentById(Integer id);
    // 根据id查询学生信息
   
}

StudentMapper.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="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="pojo.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="pojo.Clazz">
         <id property="id" column="id"/>
         <result property="code" column="code"/>
         <result property="name" column="name"/>
      </association>
   </resultMap>

</mapper>

Clazz.java

package pojo;

import java.io.Serializable;
import java.util.List;
/**
 * CREATE TABLE `tb_clazz` (
 id INT(11) PRIMARY KEY AUTO_INCREMENT,
 CODE VARCHAR(18) DEFAULT NULL,
 NAME VARCHAR(18) DEFAULT NULL
 ) COMMENT '班级表';
 INSERT INTO tb_clazz(CODE,NAME) VALUES('j1601','Java就业班');
 */


public class Clazz implements Serializable {
   
   private Integer id; // 班级id,主键
   private String code; // 班级编号
   private String name; // 班级名称

   private List<Student> students;
    // 班级和学生是一对多的关系,即一个班级可以有多个学生
   
   public Clazz() {
      super();
   }

   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getCode() {
      return code;
   }
   public void setCode(String code) {
      this.code = code;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public List<Student> getStudents() {
      return students;
   }
   public void setStudents(List<Student> students) {
      this.students = students;
   }

   @Override
   public String toString() {
      return "Clazz [id=" + id + ", code=" + code + ", name=" + name + "]";
   }
   
    
}

Student.java

package pojo;

import java.io.Serializable;
/**
 * CREATE TABLE `tb_student` (
 id INT(11) PRIMARY KEY AUTO_INCREMENT,
 NAME VARCHAR(18) DEFAULT NULL,
 sex CHAR(2) DEFAULT NULL,
 age INT(11) DEFAULT NULL,
 clazz_id INT(11),
 FOREIGN KEY (clazz_id) REFERENCES tb_clazz(id)
 ) COMMENT '学生表';
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('jack','男',23,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('rose','女',18,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('tom','男',21,1);
INSERT INTO tb_student(NAME,sex,age,clazz_id) VALUES('alice','女',20,1);
 */


public class Student implements Serializable {

   private Integer id; // 学生id,主键
   private String name; // 姓名
   private String sex;  // 性别
   private Integer age; // 年龄

   private Clazz clazz;
    // 学生和班级是多对一的关系,即一个学生只属于一个班级

   public Student() {
      super();
   }

   public Integer getId() {
      return id;
   }

   public void setId(Integer id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getSex() {
      return sex;
   }

   public void setSex(String sex) {
      this.sex = sex;
   }

   public Integer getAge() {
      return age;
   }

   public void setAge(Integer age) {
      this.age = age;
   }

   public Clazz getClazz() {
      return clazz;
   }

   public void setClazz(Clazz clazz) {
      this.clazz = clazz;
   }

   @Override
   public String toString() {
      return "Student [id=" + id + ", name=" + name + ", sex=" + sex
            + ", age=" + age + "]";
   }

   
}

log4j.properties

log4j.rootLogger=ERROR, stdout
# 全局的日志配置
log4j.logger.mapper.ClazzMapper=DEBUG
log4j.logger.mapper.StudentMapper=DEBUG
# MyBatis的日志配置
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
# 控制台输出

mybatis-config.xml

<?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.1.13:3306/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="Abcdef@123456"/>
            </dataSource>
        </environment>
    </environments>

    <!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
    <mappers>
       <mapper resource="mapper/ClazzMapper.xml"/>
       <mapper resource="mapper/StudentMapper.xml"/>
    </mappers>

</configuration>

OneToManyTest.java

import mapper.ClazzMapper;
import mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.Clazz;
import pojo.Student;
import java.io.InputStream;
import java.util.List;


public class OneToManyTest {

   public static void main(String[] args) throws Exception {
      InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 读取mybatis-config.xml文件
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
            .build(inputStream);
        // 初始化mybatis,创建SqlSessionFactory类的实例
      SqlSession session = sqlSessionFactory.openSession();
        // 创建Session实例
      OneToManyTest t = new OneToManyTest();
      
      t.testSelectClazzById(session);
//        t.testSelectStudentById(session);

      session.commit();
        // 提交事务
      session.close();
        // 关闭Session
   }

   public void testSelectClazzById(SqlSession session){
        // 测试一对多,查询班级Clazz(一)的时候级联查询学生Student(多)
      ClazzMapper cm = session.getMapper(ClazzMapper.class);
        // 获得ClazzMapper接口的代理对象
      Clazz clazz = cm.selectClazzById(1);
        // 调用selectClazzById方法
      System.out.println(clazz.getId() + " "+ clazz.getCode() + " "+clazz.getName());
        // 查看查询到的clazz对象信息
      List<Student> students = clazz.getStudents();
      for(Student stu : students){
         System.out.println(stu);
            // 查看clazz对象关联的学生信息
      }
   }

   public void testSelectStudentById(SqlSession session){
        // 测试多对一,查询学生Student(多)的时候级联查询 班级Clazz(一)
      StudentMapper sm = session.getMapper(StudentMapper.class);
        // 获得StudentMapper接口的代理对象
      Student stu = sm.selectStudentById(1);
        // 调用selectStudentById方法
      System.out.println(stu);
        // 查看查询到的Student对象信息
      System.out.println(stu.getClazz());
        // 查看Student对象关联的班级信息
   }


}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>shanghai</groupId>
    <artifactId>OneToMany</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.soureEncodng>UTF-8</maven.compiler.soureEncodng>
    </properties>

</project>

猜你喜欢

转载自blog.csdn.net/yjlch1016/article/details/80382168