MyBatis的关联映射,resultMap元素之association子元素,实现一对一关联关系(节选自:Java EE企业级应用开发教程)

MyBatis映射文件中的<resultMap>元素中,包含一个<association>子元素,MyBatis通过它来处理一对一关联关系。

association重要属性

  1. property : 映射数据库列的实体对象的属性
  2. column : 映射数据库列名或者别名
  3. javaType : 完整java类名或别名
  4. select:指定引入嵌套查询的子SQL语句
  5. fetchType:是否启用延迟加载

association子元素主要有id、result,它们具有以下属性

  1. property : 映射数据库列的实体对象的属性
  2. column : 映射数据库列名或者别名

一、创建数据结构及插入数据(MySQL),注意:请先选择数据库

# 创建一个名称为tb idcard的表
CREATE TABLE tb_idcard(
id INT PRIMARY KEY AUTO_INCREMENT,
CODE VARCHAR(18)
);

# 插入两条数据
INSERT INTO tb_idcard(CODE) VALUES('152221198711020624');
INSERT INTO tb_idcard(CODE) VALUES('152201199008150317');

# 创建一个名称为tb_person的表
CREATE TABLE tb_person(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(32),
age INT,
sex VARCHAR(8),
card_id INT UNIQUE,
FOREIGN KEY(card_id) REFERENCES tb_idcard(id)
);

# 插入两条数据
INSERT INTO tb_person(name,age,sex,card_id) VALUES ('Rose',29,'',1);
INSERT INTO tb_person(name,age,sex,card_id) VALUES ('Tom',27,'',2);

二、创建实体类IdCard/Person

package com.itheima.po;
/**
 * 证件持久化类
 */
public class IdCard {
    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;
    }
    @Override
    public String toString() {
        return "IdCard [id=" + id + ", code=" + code + "]";
    }
}
package com.itheima.po;
/**
 * 个人持久化类
 */
public class Person {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
    private IdCard 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 Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public IdCard getCard() {
        return card;
    }
    public void setCard(IdCard card) {
        this.card = card;
    }
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", "
                + "age=" + age + ", sex=" + sex + ", card=" + card + "]";
    }
}

三、创建映射文件IdCardMapper.xml和PersonMapper.xml

注意:PersonMapper.xml使用两种方式进行查询,推荐使用第二种方式(findPersonById2,嵌套结果的方式)

<?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.itheima.mapper.IdCardMapper">
  <!-- 根据id查询证件信息 -->
  <select id="findCodeById" parameterType="Integer" resultType="IdCard">
      SELECT * from tb_idcard where id=#{id}
  </select>
</mapper>
<?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.itheima.mapper.PersonMapper">
    <!-- 嵌套查询:通过执行另外一条SQL映射语句来返回预期的特殊类型 -->
    <select id="findPersonById" parameterType="Integer" 
                                      resultMap="IdCardWithPersonResult">
        SELECT * from tb_person where id=#{id}
    </select>
    <resultMap type="Person" id="IdCardWithPersonResult">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="age" column="age" />
        <result property="sex" column="sex" />
        <!-- 一对一:association使用select属性引入另外一条SQL语句 -->
        <association property="card" column="card_id" javaType="IdCard"
            select="com.itheima.mapper.IdCardMapper.findCodeById" />
    </resultMap>
    
    <!-- 嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集 -->
    <select id="findPersonById2" parameterType="Integer" 
                                       resultMap="IdCardWithPersonResult2">
        SELECT p.*,idcard.code
        from tb_person p,tb_idcard idcard
        where p.card_id=idcard.id 
        and p.id= #{id}
    </select>
    <resultMap type="Person" id="IdCardWithPersonResult2">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="age" column="age" />
        <result property="sex" column="sex" />
        <association property="card" javaType="IdCard">
            <id property="id" column="card_id" />
            <result property="code" column="code" />
        </association>
    </resultMap>
    
</mapper>

四、创建MyBatis配置文件(mybatis-config.xml)、数据库配置文件(db.properties) 、日志配置(log4j.properties)

<typeAliases>元素的作用,是为配置文件中的Java类型设置一个简短的名字,即设置别名。当POJO类过多时,它还可以通过自动扫描包的形式自定义别名,本配置文件即采用此种方式:
它自动将com.itheima.po.IdCard设置为idCard,com.itheima.po.Person设置为person等等。
 
<?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>
    <!-- 引入数据库连接配置文件 -->
    <properties resource="db.properties" />
    
    <settings>
     <!-- 打开延迟加载的开关 -->  
    <setting name="lazyLoadingEnabled" value="true" />  
    <!-- 将积极加载改为消息加载,即按需加载 -->  
    <setting name="aggressiveLazyLoading" value="false"/>  
    </settings>
    
    <!--使用扫描包的形式定义别名 -->
    <typeAliases>
        <package name="com.itheima.po" />
    </typeAliases>
    <!--配置环境 ,默认的环境id为mysql -->
    <environments default="mysql">
        <!-- 配置id为mysql的数据库环境 -->
        <environment id="mysql">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <!--数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!--配置Mapper的位置 -->
     <mappers>
         <mapper resource="com/itheima/mapper/IdCardMapper.xml" />
         <mapper resource="com/itheima/mapper/PersonMapper.xml" />
         <mapper resource="com/itheima/mapper/UserMapper.xml" />
         <mapper resource="com/itheima/mapper/OrdersMapper.xml" />
          <mapper resource="com/itheima/mapper/ProductMapper.xml" />
     </mappers>
</configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xuejia
jdbc.username=root
jdbc.password=admin

 log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.itheima=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

五、创建测试程序MybatisAssociatedTest.java

package com.itheima.test;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.itheima.po.Orders;
import com.itheima.po.Person;
import com.itheima.po.User;
import com.itheima.utils.MybatisUtils;
/**
 * Mybatis关联查询映射测试类
 */
public class MybatisAssociatedTest {
    /**
     * 嵌套查询
     */
    @Test
    public void findPersonByIdTest() {
        // 1、通过工具类生成SqlSession对象
        SqlSession session = MybatisUtils.getSession();
        // 2.使用MyBatis嵌套查询的方式查询id为1的人的信息
        Person person = session.selectOne("com.itheima.mapper." 
                                   + "PersonMapper.findPersonById", 1);
        // 3、输出查询结果信息
        System.out.println(person);
        // 4、关闭SqlSession
        session.close();
    }
    
    /**
     * 嵌套结果
     */
    @Test
    public void findPersonByIdTest2() {
        // 1、通过工具类生成SqlSession对象
        SqlSession session = MybatisUtils.getSession();
        // 2.使用MyBatis嵌套结果的方法查询id为1的人的信息
        Person person = session.selectOne("com.itheima.mapper." 
                                   + "PersonMapper.findPersonById2", 1);
        // 3、输出查询结果信息
        System.out.println(person);
        // 4、关闭SqlSession
        session.close();
    }
}

六、工具类参考MybatisUtils.java

package com.itheima.utils;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
 * 工具类
 */
public class MybatisUtils {    
    public static SqlSessionFactory sqlSessionFactory = null;
    // 初始化SqlSessionFactory对象
    static{
        try {
            //使用MyBatis提供的Resources类加载mybatis的配置文件
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            //构建sqlSession的工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 获取SqlSession对象的静态方法
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }
}

七、运行结果

DEBUG [main] - ==>  Preparing: SELECT p.*,idcard.code from tb_person p,tb_idcard idcard where p.card_id=idcard.id and p.id= ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
Person [id=1, name=Rose, age=29, sex=女, card=IdCard [id=1, code=152221198711020624]]
DEBUG [main] - ==>  Preparing: SELECT * from tb_person where id=? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - ==>  Preparing: SELECT * from tb_idcard where id=? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
Person [id=1, name=Rose, age=29, sex=女, card=IdCard [id=1, code=152221198711020624]]

 

posted @ 2021-08-19 12:52  那些年的事儿  阅读(1255)  评论(0编辑  收藏  举报