欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MyBatis3一对多关系映射

程序员文章站 2022-07-13 16:15:11
...
1. MyBatis3关系映射,一对多关系

创建t_grade数据表
create table t_grade(
id int(11) NOT NULL AUTO_INCREMENT,
gradeName varchar(20) DEFAULT NULL,
PRIMARY KEY(id)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

插入数据
insert into t_grade(id, gradeName) values(1, '大学一年级');
insert into t_grade(id, gradeName) values(2, '大学二年级');

在t_student表增加gradeId关联字段
alter table t_student add gradeId INT(11);


2. 使用mybatis查询关联表使用collection 方式,一对多关系

<resultMap type="Grade" id="GradeResult">
    <result property="id" column="id"/>
    <result property="gradeName" column="gradeName"/>
    <collection property="students" column="id" select="com.andrew.mappers.StudentMapper.findByGradeId"></collection>
</resultMap>


3. 使用mybatis查询关联表,一对多关系

package com.andrew.model;
import java.util.List;
public class Grade {
    private Integer id;
    private String gradeName;
    private List<Student> students;
    @Override
    public String toString() {
        return "Grade [id=" + id + ", gradeName=" + gradeName +", student=" + students + "]";
    }
    // getter and setter
}


package com.andrew.mappers;
import com.andrew.model.Grade;
public interface GradeMapper {
    public Grade findById(Integer id);
}


<?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.andrew.mappers.GradeMapper">
    <resultMap type="Grade" id="GradeResult">
        <result property="id" column="id"/>
        <result property="gradeName" column="gradeName"/>
        <collection property="students" column="id" select="com.andrew.mappers.StudentMapper.findByGradeId"></collection>
    </resultMap>
    <select id="findById" parameterType="Integer" resultMap="GradeResult">
        select * from t_grade where id=#{id}
    </select>
</mapper>


package com.andrew.mappers;
import java.util.List;
import com.andrew.model.Student;
public interface StudentMapper {
    public int add(Student student);
    public int update(Student student);
    public int delete(Integer id);
    public Student findById(Integer id);
    public List<Student> find();
    public Student findStudentWithAddress(Integer id);
    public Student findByGradeId(Integer gradeId);
}


<?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.andrew.mappers.StudentMapper">
    <resultMap type="Student" id="StudentResult">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
    </resultMap>
    <resultMap type="Student" id="StudentAddressResult">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <association property="address" column="addressId" select="com.andrew.mappers.AddressMapper.findById"></association>
        <association property="grade" column="gradeId" select="com.andrew.mappers.GradeMapper.findById"></association>
    </resultMap>
    <insert id="add" parameterType="Student">
        insert into t_student values(null, #{name}, #{age})
    </insert>
    <update id="update" parameterType="Student">
        update t_student set name=#{name},age=#{age} where id=#{id}
    </update>
    <delete id="delete" parameterType="Integer">
        delete from t_student where id=#{id}
    </delete>
    <select id="findById" parameterType="Integer" resultType="Student">
        select * from t_student where id=#{id}
    </select>
    <select id="find" resultMap="StudentAddressResult">
        select * from t_student
    </select>
    <select id="findStudentWithAddress" resultMap="StudentAddressResult" parameterType="Integer">
        select * from t_student t1,t_address t2 where t1.addressId=t2.id and t1.id=#{id}
    </select>
    <select id="findByGradeId" resultMap="StudentAddressResult" parameterType="Integer">
        select * from t_student where gradeId=#{gradeId}
    </select>
</mapper> 


package com.andrew.model;
public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private Address address;
    private Grade grade;
    public Student() {
        super();
    }
    public Student(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Student(Integer id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age
                + ", address=" + address + "]";
    }
    // getter and setter
}


package com.andrew.service;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.andrew.mappers.GradeMapper;
import com.andrew.model.Grade;
import com.andrew.util.SqlSessionFactoryUtil;
public class StudentGradeTest {
    private static Logger logger = Logger.getLogger(StudentTest.class);
    private SqlSession sqlSession = null;
    private GradeMapper gradeMapper = null;
    @Before
    public void setUp() throws Exception {
        sqlSession = SqlSessionFactoryUtil.openSession();
        gradeMapper = sqlSession.getMapper(GradeMapper.class);
    }
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }
    @Test
    public void testFindGradeWithStudents() {
        logger.info("查询年级和学生");
        Grade grade = gradeMapper.findById(2);
        System.out.println(grade);
    }
}

运行结果:
Grade [id=2, gradeName=大学二年级, student=[Student [id=7, name=赵六3, age=23, address=Address [id=1, sheng=北京市, shi=北京市, qu=东城区]], Student [id=9, name=赵六5, age=25, address=Address [id=1, sheng=北京市, shi=北京市, qu=东城区]]]]

注意:
一对多关系不能a调用b的同时b调用a,否则会有死循环。
可以不使用默认的toString方法,自定义不同的方法。
相关标签: mybatis