【Mybatis】级联查询之一对一级联查询

本文目录

  • 引言
  • 创建工程和数据库表
  • 创建实体类和数据库操作接口
    • IdCard 类
    • User类
    • IdCardMapper
    • UserMapper
  • 创建配置文件
    • mybatis-config.xml
    • IdCardMapper.xml
    • UserMapper.xml
      • 方法1
      • 方法2
      • 方法3
  • 添加测试代码

引言

前面讲resultMap元素时, 【Mybatis】配置映射文件之resultMap元素和resultType元素,该元素包含了一个子元素association,Mybatis 主要通过该元素处理一对一关联关系。
association元素中,通常可以配置以下属性

  • property:指定映射到实体类的对象属性。
  • column:指定表中对应的字段(即查询返回的列名)。
  • javaType:指定映射到实体对象属性的类型。
  • select:指定引入嵌套查询的子 SQL 语句,该属性用于关联映射中的嵌套查询

应用场景举例:人与身份证之间的关系为一对一,即一个人只能拥有一个身份证,一个身份证只能对应一个人。

创建工程和数据库表

创建Spring整合Mybatis工程 【Spring】Spring整合Mybatis案例

创建idcard表和user

DROP TABLE IF EXISTS `idcard`;
CREATE TABLE `idcard` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(25) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user` (
  `card_id` int(11) DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `card_id` (`card_id`),
  CONSTRAINT `card_id` FOREIGN KEY (`card_id`) REFERENCES `idcard` (`id`) ON DELETE SET NULL
) 

项目结构如下:
【Mybatis】级联查询之一对一级联查询_第1张图片

创建实体类和数据库操作接口

IdCard 类

public class IdCard {
     
    private int id;
    private String code;

    public int getId() {
     
        return id;
    }

    public void setId(int 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 + '\'' +
                '}';
    }
}

User类

public class User {
     
    private int id;
    private String name;
    private int age;
    private IdCard idcard;

    public int getId() {
     
        return id;
    }

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

    public String getName() {
     
        return name;
    }

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

    public int getAge() {
     
        return age;
    }

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

    public IdCard getIdcard() {
     
        return idcard;
    }

    public void setIdcard(IdCard idcard) {
     
        this.idcard = idcard;
    }

    @Override
    public String toString() {
     
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", idcard=" + idcard +
                '}';
    }
}

IdCardMapper

@Repository("idCardMapper")
@Mapper
public interface IdCardMapper {
     
    IdCard findCardById(int id);
}

UserMapper

@Repository("userMapper")
@Mapper
public interface UserMapper {
     
    List<User> findAllUser();
}

创建配置文件

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>
        <!--在使用MyBatis嵌套查询方式进行关联查询时,使用MyBatis的延迟加载可以在一定程度上提高查询效率-->
        <!--打开延迟加载的开关-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--将积极加载改为按需加载-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <mappers>
        <mapper resource="UserMapper.xml"/>
        <mapper resource="IdCardMapper.xml"/>
    </mappers>

</configuration>

IdCardMapper.xml



<mapper namespace="com.lucas.mybatis.mapper.IdCardMapper">
    <select id="findCardById" parameterType="Integer" resultType="com.lucas.mybatis.model.IdCard" >
        select  * from idcard where id=#{id}
    select>

mapper>

UserMapper.xml

方法1



<mapper namespace="com.lucas.mybatis.mapper.UserMapper">
    
    <resultMap type="com.lucas.mybatis.model.User" id="cardAndUser">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        
        
        <association property="idcard" column="card_id"
                     javaType="com.lucas.mybatis.model.IdCard" select="com.lucas.mybatis.mapper.IdCardMapper.findCardById"/>
    resultMap>
    
    <select id="findAllUser"   resultMap="cardAndUser">
			select * from user
	select>

mapper>

方法2



<mapper namespace="com.lucas.mybatis.mapper.UserMapper">

    <resultMap type="com.lucas.mybatis.model.User" id="cardAndUser">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        
        <association property="idcard" javaType="com.lucas.mybatis.model.IdCard" column="card_id">
            
            <id property="id" column="card_id"/>
            <result property="code" column="code"/>
        association>
    resultMap>
    
    <select id="findAllUser"  resultMap="cardAndUser">
		select user.*,idcard.code
		from `user`,idcard
		where user.card_id=idcard.id
		select>
mapper>

方法3



<mapper namespace="com.lucas.mybatis.mapper.UserMapper">
   <select id="findAllUser" resultType="com.lucas.mybatis.model.UserPojo" >
          select user.*,idcard.code from `user`,idcard where user.card_id=idcard.id 
       select>
mapper>

UserPojo

public class UserPojo {
     
    private int id;
    private String name;
    private int age;
    private String code;

    public int getId() {
     
        return id;
    }

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

    public String getName() {
     
        return name;
    }

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

    public int getAge() {
     
        return age;
    }

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

    public String getCode() {
     
        return code;
    }

    public void setCode(String code) {
     
        this.code = code;
    }

    @Override
    public String toString() {
     
        return "UserPojo{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", code='" + code + '\'' +
                '}';
    }
}

添加测试代码

public class App {
     
    public static void main(String[] args) {
     
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
       List<User> users = userMapper.findAllUser();
       for (User user :users){
     
           System.out.println(user);
       }
    }
}

【Mybatis】级联查询之一对一级联查询_第2张图片

你可能感兴趣的:(JavaEE,#,Spring,#,Mybatis,java,mybatis,mysql,数据库)