首页 > 其他分享 >Mybatis使用注解实现一对一复杂关系映射及延迟加载

Mybatis使用注解实现一对一复杂关系映射及延迟加载

时间:2023-02-13 11:36:12浏览次数:54  
标签:映射 void private public org Mybatis import id 加载

一、问题引入:

在加载账户信息时同时加载该账户的用户信息,根据情况可实现延时加载(注解方式实现)
数据库字段如下:
user表:
Mybatis使用注解实现一对一复杂关系映射及延迟加载_mysqlaccount表:
Mybatis使用注解实现一对一复杂关系映射及延迟加载_mybatis_02

二、添加User实体类和Account类

user.java:

package com.itheima.domain;

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

public class User implements Serializable {

    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;
//  一对多关系映射:一个用户对应多个账户
    private List<Account> accounts;

    public List<Account> getAccounts() {
        return accounts;
    }

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

Account.java

package com.itheima.domain;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;

    //多对一(Mybatis称之为1对1)的映射:一个账户只能属于一个用户
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Integer getId() {
        return id;
    }

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

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                '}';
    }
}

三、添加账户的持久层接口并使用注解配置:

package com.itheima.dao;

import com.itheima.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface IAccountDao {

    /*
    * 查询所有账户,并且获取每个账户所属的用户信息
    * */
    @Select("select * from account")
    @Results(id = "accountMap",value={
            @Result(id =true,column = "id",property = "id"),
            @Result(column = "uid",property = "uid"),
            @Result(column = "money",property = "money"),
            @Result(property = "user",column = "uid",one = @One(select="com.itheima.dao.IUserDao.findById",fetchType= FetchType.EAGER))
    })
    List<Account> findAll();

//根据用户id查询账户信息
    @Select("select * from account where uid=#{userId}")
    List<Account> findAccountByUid(Integer userId);
}

四、添加用户的持久层接口并使用注解配置

package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;
/*
* 在mybatis针对CRUD一共有四个注解
* @Select @Insert @Update @Delete
* */
@CacheNamespace(blocking = true)
public interface IUserDao {
/*当属性名称和数据库中字段名不一致时,用@results和@result注解*/
    //查询所有用户
    @Select("select * from user")
    @Results(id = "userMap",value ={
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "address",property = "address"),
            @Result(column = "sex",property = "sex"),
            @Result(column = "birthday",property = "birthday"),
            @Result(property = "accounts",column = "id",
                    many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
                            fetchType = FetchType.LAZY))
    })
    List<User> findAll();

    /*
    * 根据id查询用户
    * */
    @Select("select * from user where id=#{id}")
    User findById(Integer userId);

    //根据用户名称模糊查询
    @Select("select * from user where username like #{username}")
    List<User> findUserByName(String username);


}

五、测试类

package com.itheima.test;

import com.itheima.dao.IAccountDao;
import com.itheima.dao.IUserDao;
import com.itheima.domain.Account;
import com.itheima.domain.User;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class AccountTest {
    private SqlSessionFactory factory;
    private SqlSession session;
    private IAccountDao accountDao;
    private InputStream in;
    @Before
    public void init() throws Exception{
        in= Resources.getResourceAsStream("SqlMapConfig.xml");
        factory=new SqlSessionFactoryBuilder().build(in);
        session=factory.openSession();
        accountDao=session.getMapper(IAccountDao.class);
    }

    @After
    public void destroy() throws Exception{
        session.commit();
        session .close();
        in.close();
    }
    @Test
    public void testFindAll() {
        List<Account> accounts = accountDao.findAll();
        for (Account account : accounts) {
            System.out.println("-----每个账户的信息-----");
            System.out.println(account);
            System.out.println(account.getUser());
        }
    }
}

六、运行结果

Mybatis使用注解实现一对一复杂关系映射及延迟加载_maven_03

标签:映射,void,private,public,org,Mybatis,import,id,加载
From: https://blog.51cto.com/u_15961549/6053823

相关文章

  • Mybatis注解开发
    环境搭建单表CRUD操作(代理Dao方式)多表查询操作缓存的配置总结:mybatis的环境搭建第一步:创建maven工程并导入坐标第二步:创建实体类和dao的接口第三步:创建My......
  • mybatis 表与表 关联查询 (一)
     @MapperpublicinterfaceDeptMapper{/***分步查询员工*及员工所对应的部门*分步查询第二步:*通过部门查询员工所对应的部门......
  • Spring+MyBatis整合步骤
    一、两者整合的主要工作:把MyBatis框架中使用到的核心对象(组件)配置到Spring中,交给Spring来创建管理;具体来说:将MyBatis匹配文件中的数据源、SQL映射文件、SqlSessionFactoryBu......
  • Mybatis-尚硅谷-学习笔记
    https://blog.csdn.net/weixin_45581692/article/details/127508494?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522167619048716800188527496%2522%252C%2522......
  • mybatis逆向工程用法
    官网所在的地址:http://mybatis.org/generator/quickstart.html#MyBatis3DynamicSql第一件事,导入相关的包(注意版本,下面仅供参考)<!--代码生成器--><!--......
  • react实战笔记79:加载meals数据2
     通过父子传值处理......
  • Spring Boot+Mybatis-1:集成 Mybatis 并实现 CRUD(1)
    读前需知:此系列属于个人学习过程中的学习记录,不保证是最优方案,请读者大佬们带点批判进行阅读。如有技术上的错误望不吝赐教~1.前言MyBatis是一款持久层框架,它支持自定义......
  • MyBatis_01(前置知识)
    1-学习思路(课程主要内容):2-MyBatis特性3-MyBatis下载但是我们在使用MyBatis的时候,都是直接"Maven导入MyBatis的jar包"(所以,这个下载只是为了看"Mybatis"的官方文档......
  • MyBatis批量插入的五种方式,哪种最强???
    前言:这里我列举了MyBatis和MyBatis-Plus常用的五种批量插入的方式,进行了详细的总结归纳,写的非常详细,整体思路清晰明了,只分享干货。目录一、准备工作二、MyBatis利......
  • 【JVM】Class文件加载过程
    1 前言JVM的入口数据就是每一个Class文件,我们上一篇,仔细分析了Class文件中的每个字节所代表的含义,那么它是如何加载进JVM的,这一篇我们来讲解。Class文件的解释运行时数......