栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MyBatis-映射关系

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MyBatis-映射关系

MyBatis-映射关系 1.映射关系一对一 1.映射关系-官方文档

文档地址: https://mybatis.org/mybatis-3/zh/sqlmap-xml.html

2.映射关系1对1-基本介绍

● 基本介绍

  1. 项目中 1 对 1 的关系是一个基本的映射关系,比如:Person(人) — IDCard(身份证)
-- 创建 mybatis_idencard 表
CREATE TABLE idencard ( id INT PRIMARY KEY AUTO_INCREMENT, card_sn VARCHAr ( 32 ) NOT NULL DEFAULT '' ) CHARSET utf8;
CREATE TABLE person (
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAr ( 32 ) NOT NULL DEFAULT '',
	card_id INT,
FOREIGN KEY ( card_id ) REFERENCES idencard ( id ) 
) CHARSET utf8;

INSERT INTO idencard
VALUES
	( 1, '111111111111110' );
INSERT INTO person
VALUES
	( 1, '张三', 1 );
	
SELECt * FROM person; 
SELECt * FROM idencard
  1. 创建新的 module(mybatis-mapping), 相关配置文件可以从上一个 module 拷贝

​ 3.创建srcmainjavacomllpentityIdenCard.java

@Data
public class IdenCard {
    private Integer id;
    private String card_sn;
}

​ 4.创建srcmainjavacomllpentityPerson.java

@Data
public class Person {
    private Integer id;
    private String name;
    //因为我们的需要实现一个级联操作, 一个人需要对应一个身份证
    //这里需要直接定义IdenCard对象属性
    private IdenCard card;
}

​ 5.创建PersonMapper.java和IdenCardMapper.java

public interface PersonMapper {
    Person getPersonById(Integer id);
}

public interface IdenCardMapper {
    IdenCard getIdenCardById(Integer id);
}

​ 6.创建PersonMapper.xml和IdenCardMapper.xml

IdenCardMapper.xml




    

    SELECT * FROM `idencard` WHERe `id` = #{id}


PersonMapper.xml




    

   select * from person where id = #{id}

去获取person对象时,发现mybatis并不能将person类中的IdenCard对象的值映射到card属性中,由此就引出了处理1对1的映射方式

3.映射关系 1 对 1-映射方式 1.映射方式
  1. 通过配置 XxxMapper.xml 实现 1 对 1 [配置方式]
  2. 通过注解的方式实现 1 对 1 [注解方式]
2.配置 Mapper.xml 的方式-应用实例 1.方式1

说明:通过配置 XxxMapper.xml 的方式来实现下面的 1 对 1 的映射关系,实现级联查询,通过 person 可以获取到对应的 idencard 信息

1.修改PersonMapper.xml



       
   
   
    
   
   
   
   


   select * from person,idencard where person.id = #{id} and person.card_id=idencard.id

2.测试方法

@Test
public void getPersonById(){
    Person personById = personMapper.getPersonById(1);
    //Person(id=1, name=张三, card=IdenCard(id=1, card_sn=111111111111110))
    System.out.println(personById);
}
2.方式2

1.修改PersonMapper.xml

    
	
		
		
        

		
	
	
        SELECT * FROM `mybatis_pet` WHERe `user_id` = #{userId}
    

    
    
        SELECT * FROM `mybatis_user` WHERe `id` = #{id}
    

5.创建UserMapperTest.java和PetMapperTest.java测试类

PetMapperTest.java

@Test
public void getPetByUserId() {
    List pets = petMapper.getPetByUserId(2);
    for (Pet pet : pets) {
        System.out.println("pet信息-" + pet.getId() + "-" + pet.getNickName());
        User user = pet.getUser();
        System.out.println("user信息 name-" + user.getName());
    }
    if(sqlSession != null) {
        sqlSession.close();
    }
}
@Test
public void getPetById() {
    Pet pet = petMapper.getPetById(2);
    System.out.println("pet信息-" + pet.getId() + "-" + pet.getNickName());
    User user = pet.getUser();
    System.out.println("user信息-" + user.getId() + "-" + user.getName());
    if(sqlSession != null) {
        sqlSession.close();
    }
}

UserMapperTest.java

    @Test
    public void getUserById() {
        User user = userMapper.getUserById(2);

        System.out.println("user信息-" + user.getId() + "-" + user.getName());

        List pets = user.getPetList();
        for (Pet pet : pets) {
            System.out.println("养的宠物信息-" + pet.getId() + "-" + pet.getNickName());
        }
        if(sqlSession != null) {
            sqlSession.close();
        }
    }

3.注解实现多对1映射-应用实例

需求说明: 通过注解的方式来实现下面的多对 1 的映射关系,实现级联查询,完成前面完成 的任务,通过 User–>Pet 也可 Pet->User , 在实际开发中推荐使用配置方式来做

1.创建srcmainjavacomllpmapperPetMapperAnnotation.java

public interface PetMapperAnnotation {

    
    @Select(value = "SELECT * FROM mybatis_pet where user_id=#{userId}")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "nickname", property = "nickName"),
            @Result(property = "user", column = "user_id", one = @One(select = "com.llp.mapper.MyBatisUserMapper.getUserById"))
    })
    List getPetByUserId(Integer userId);

    @Select(value = "SELECT * FROM mybatis_pet where id=#{id}")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "nickname", property = "nickName"),
            @Result(property = "user", column = "user_id",  
                    one = @One(select = "com.llp.mapper.MyBatisUserMapper.getUserById"))
    })
    Pet getPetById(int id);

}

2.创建srcmainjavacomllpmapperUserMapperAnnotation.java

public interface UserMapperAnnotation {

    
    @Select("select * from mybatis_user where id = #{id}")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "name",property = "name"),
            @Result(column = "id",property = "petList",many = @Many(select ="com.llp.mapper.PetMapper.getPetByUserId"))
    })
    User getUserById(Integer id);
}

3.测试方法

PetMapperAnnotationTest.java

@Test
public void getPetByUserId(){
    List pets = personMapperAnnotation.getPetByUserId(2);
    for (Pet pet : pets) {
        System.out.println("pet信息-" + pet.getId() + "-" + pet.getNickName());
        User user = pet.getUser();
        System.out.println("user信息 name-" + user.getName());
    }
    if(sqlSession != null) {
        sqlSession.close();
    }
}

@Test
public void getPetById() {
    Pet pet = personMapperAnnotation.getPetById(2);
    System.out.println("pet信息-" + pet.getId() + "-" + pet.getNickName());
    User user = pet.getUser();
    System.out.println("user信息-" + user.getId() + "-" + user.getName());
    if(sqlSession != null) {
        sqlSession.close();
    }
}

UserMapperAnnotationTest

@Test
public void getUserById() {
    User user = userMapperAnnotation.getUserById(2);

    System.out.println("user信息-" + user.getId() + "-" + user.getName());

    List pets = user.getPetList();
    for (Pet pet : pets) {
        System.out.println("养的宠物信息-" + pet.getId() + "-" + pet.getNickName());
    }
    if(sqlSession != null) {
        sqlSession.close();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1007613.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号