mybatis 关联映射

一对一

创建数据表

CREATE TABLE `tb_card` (
`id`  int NOT NULL AUTO_INCREMENT ,
`code`  varchar(18) NULL ,
PRIMARY KEY (`id`)
);
insert into tb_card(code) values('123456');
CREATE TABLE tb_person(id int not null PRIMARY KEY auto_increment,name VARCHAR(18),sex VARCHAR(18),age int,card_id int UNIQUE);
INSERT INTO tb_person(name,sex,age,card_id) VALUES('jack','',23,1);
View Code

目录结构

 

Card

package com.example.demo.domain;

import java.io.Serializable;

public class Card implements Serializable {
    private Integer id;
    private String code;

    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;
    }
}
View Code

Person

package com.example.demo.domain;

import java.io.Serializable;

public class Person implements Serializable {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
    private Card card;

    public Card getCard() {
        return card;
    }

    public void setCard(Card card) {
        this.card = card;
    }

    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;
    }
}
View Code

CardMapper

package com.example.demo.mapper;

import com.example.demo.domain.Card;

public interface CardMapper {
    Card selectCardById(Integer id);
}
View Code

PersonMapper

package com.example.demo.mapper;

import com.example.demo.domain.Person;

public interface PersonMapper {
    Person selectPersonById(Integer id);
}
View Code

CardMapper.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.example.demo.mapper.CardMapper">
    <!--<insert id="save" parameterType="com.example.demo.domain.Card" useGeneratedKeys="true">-->
        <!--INSERT INTO tb_card(code) VALUES (#{code})-->
    <!--</insert>-->
    <select id="selectCardById" parameterType="int" resultType="com.example.demo.domain.Card">
        SELECT  *  FROM tb_card WHERE id=#{id}
    </select>
</mapper>
View Code

PersonMapper.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.example.demo.mapper.PersonMapper">
    <!--<insert id="save" parameterType="com.example.demo.domain.Person" useGeneratedKeys="true">-->
        <!--INSERT INTO tb_person(name,sex,age,card_id) VALUES (#{name},#{sex},#{age},#{card_id})-->
    <!--</insert>-->
    <select id="selectPersonById" parameterType="int" resultMap="personMapper">
        SELECT  *  FROM tb_person WHERE id=#{id}
    </select>
    <resultMap id="personMapper" type="com.example.demo.domain.Person">
        <id property="id" column="id"></id>
        <result property="name" column="name"></result>
        <result property="sex" column="sex"></result>
        <result column="age" property="age"></result>
        <association property="card" column="card_id" select="com.example.demo.mapper.CardMapper.selectCardById"
                     javaType="com.example.demo.domain.Card"></association>
    </resultMap>
</mapper>
View Code

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">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.31.146:3306/mydb"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="CardMapper.xml"></mapper>
        <mapper resource="PersonMapper.xml"></mapper>
    </mappers>
</configuration>
View Code

OnoToOneTest

package com.example.demo.test;

import com.example.demo.domain.Person;
import com.example.demo.mapper.PersonMapper;
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 java.io.IOException;
import java.io.InputStream;

public class OnoToOneTest {
    public static void main(String[] args) throws IOException {
        InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session=factory.openSession();
        PersonMapper pm=session.getMapper(PersonMapper.class);
        Person p=pm.selectPersonById(1);
        System.out.println(p);
        System.out.println(p.getCard());
        session.commit();
        session.close();
    }
}
View Code

运行结果:

 

这里特别需要注意的是CardMapper.xml和PersonMapper.xml的位置。

 

一对多

Clazz

package com.example.demo.domain;

import java.io.Serializable;
import java.util.List;

public class Clazz implements Serializable {
    private Integer id;
    private String code;
    private String name;
    private List<Student> students;

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    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;
    }
}
View Code

Student

package com.example.demo.domain;

import java.io.Serializable;

public class Student implements Serializable {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
    private Clazz clazz;

    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;
    }
}
View Code

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">
<mapper namespace="com.example.demo.mapper.ClazzMapper">

    <select id="selectClazzById" parameterType="int"
            resultMap="clazzResultMap">
        SELECT  *  FROM tb_clazz WHERE id=#{id}
    </select>
    <resultMap id="clazzResultMap" type="com.example.demo.domain.Clazz">
        <id column="id" property="id"></id>
        <result property="code" column="code"></result>
        <result column="name" property="name"></result>
        <collection property="students" javaType="ArrayList" column="id" ofType="com.example.demo.domain.Student"
                    select="com.example.demo.mapper.StudentMapper.selectStudentByClazzId" fetchType="lazy">
            <id property="id" column="id"></id>
            <result property="name" column="name"></result>
            <result property="sex" column="sex"></result>
            <result property="age" column="age"></result>
        </collection>
    </resultMap>
</mapper>
View Code

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">
<mapper namespace="com.example.demo.mapper.StudentMapper">

    <select id="selectStudentById" parameterType="int" resultType="com.example.demo.domain.Student">
        SELECT  *  FROM tb_Student WHERE id=#{id}
    </select>
    <select id="selectStudentByClazzId" parameterType="int" resultType="com.example.demo.domain.Student">
        SELECT * FROM  tb_student WHERE clazz_id=#{id}
    </select>
</mapper>
View Code

ClazzMapper

package com.example.demo.mapper;

import com.example.demo.domain.Clazz;

public interface ClazzMapper {
    Clazz selectClazzById(Integer id);
}
View Code

StudentMapper

package com.example.demo.mapper;

import com.example.demo.domain.Student;

public interface StudentMapper {
    Student selectStudentByClazzId(Integer id);
}
View Code

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">
<configuration>
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.31.146:3306/mydb"/>
                <property name="username" value="root"/>
                <property name="password" value="weiwei1207"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="CardMapper.xml"></mapper>
        <mapper resource="PersonMapper.xml"></mapper>
        <mapper resource="ClazzMapper.xml"></mapper>
        <mapper resource="StudentMapper.xml"></mapper>
    </mappers>

</configuration>
View Code

注意这里添加了settings配置延迟加载

OneToManyTest

package com.example.demo.test;

import com.example.demo.domain.Clazz;
import com.example.demo.domain.Student;
import com.example.demo.mapper.ClazzMapper;
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 java.io.IOException;
import java.io.InputStream;

public class OneToManyTest {
    public static void main(String[] args) throws IOException {
        InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session=factory.openSession();
        ClazzMapper mapper=session.getMapper(ClazzMapper.class);
        Clazz clazz=mapper.selectClazzById(1);
        System.out.println(clazz.getId()+" "+clazz.getCode()+" "+clazz.getName());
        for(Student student:clazz.getStudents()){
            System.out.println(student.getId()+" "+student.getName());
        }
    }
}
View Code

数据库

 

运行结果

 

修改StudentMapper

package com.example.demo.mapper;

import com.example.demo.domain.Student;

public interface StudentMapper {
    Student selectStudentByClazzId(Integer id);
    Student selectStudentById(Integer id);
}
View Code

修改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">
<mapper namespace="com.example.demo.mapper.StudentMapper">

    <select id="selectStudentById" parameterType="int" resultMap="studentResultMap">
        SELECT  *  FROM tb_student a JOIN tb_clazz b ON a.clazz_id=b.id WHERE a.id=#{id}
    </select>
    <resultMap id="studentResultMap" type="com.example.demo.domain.Student">
        <id property="id" column="id"></id>
        <result property="name" column="name"></result>
        <result property="sex" column="sex"></result>
        <result property="age" column="age"></result>
        <association property="clazz" javaType="com.example.demo.domain.Clazz">
            <id property="id" column="id"></id>
            <result property="code" column="code"></result>
            <result column="name" property="name"></result>
        </association>
    </resultMap>
    <select id="selectStudentByClazzId" parameterType="int" resultType="com.example.demo.domain.Student">
        SELECT * FROM  tb_student WHERE clazz_id=#{id}
    </select>
</mapper>
View Code

修改OneToManyTest

StudentMapper mapper=session.getMapper(StudentMapper.class);
        Student student=mapper.selectStudentById(1);
        System.out.println(student.getId()+" "+student.getName()+" "+student.getClazz().getCode()+" "+student.getClazz().getName());
View Code

运行

 

posted @ 2017-12-14 23:17  uptothesky  阅读(156)  评论(0编辑  收藏  举报