首页 > 其他分享 >Mybatis使用注解实现一对多复杂关系映射

Mybatis使用注解实现一对多复杂关系映射

时间:2023-02-13 11:37:45浏览次数:41  
标签:映射 void private public user import Mybatis 注解 id

一、问题引入:

查询用户信息时,将用户的所有账户也查询出来,使用注解方式实现
(一个账户具有多个用户信息,所以形成了用户和账户之间的一对多关系)
account表
Mybatis使用注解实现一对多复杂关系映射_数据库
user表:
Mybatis使用注解实现一对多复杂关系映射_数据库_02

二、 User实体类:

User.java:(加入 List< Account >)

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 +
                '}';
    }
}

三、持久层接口:

IUserDao.java(用户的持久层接口):
里面的FetchType.LAZY(这个意思是延迟加载)

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);


}

IAccountDao.java(账户的持久层接口)

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.test;

import com.itheima.dao.IUserDao;
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.Date;
import java.util.List;

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

    @After
    public void destroy() throws Exception{
        session.commit();
        session .close();
        in.close();
    }
    @Test
    public void testFindAll(){
        List<User> users=userDao.findAll();
        for(User user:users){
            System.out.println("-----每个用户的信息-----");
            System.out.println(user);
            System.out.println(user.getAccounts());
        }
    }
    @Test
    public void testFindOne(){
        User user=userDao.findById(56);
        System.out.println(user);
    }

    @Test
    public void testFindByName(){
        List<User> users=userDao.findUserByName("%mybatis%");
        for(User user:users){
            System.out.println(user);
        }
    }


}

五、运行结果(这里用了延时加载)

Mybatis使用注解实现一对多复杂关系映射_java_03

标签:映射,void,private,public,user,import,Mybatis,注解,id
From: https://blog.51cto.com/u_15961549/6053821

相关文章

  • Mybatis使用注解实现一对一复杂关系映射及延迟加载
    一、问题引入:在加载账户信息时同时加载该账户的用户信息,根据情况可实现延时加载(注解方式实现)数据库字段如下:user表:account表:二、添加User实体类和Account类us......
  • Mybatis注解开发
    环境搭建单表CRUD操作(代理Dao方式)多表查询操作缓存的配置总结:mybatis的环境搭建第一步:创建maven工程并导入坐标第二步:创建实体类和dao的接口第三步:创建My......
  • mybatis 表与表 关联查询 (一)
     @MapperpublicinterfaceDeptMapper{/***分步查询员工*及员工所对应的部门*分步查询第二步:*通过部门查询员工所对应的部门......
  • 引入切面注解@Aspect依赖
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId><scope>test</scope>......
  • 五.注解配置SpringMVC
    使用配置类和注解代替web.xml和SpringMVC配置文件的功能1、创建初始化类,代替web.xml在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerlnitialize......
  • 用注解实现AOP
    一、@Aspect:切面类@Before:前置@Around:环绕@AfterRetuming:后置@AfterThrowing:异常@After:最终@Pointcut:连接点,标注在一个无返、无参、二、加载<context:component-scanbase-p......
  • Spring+MyBatis整合步骤
    一、两者整合的主要工作:把MyBatis框架中使用到的核心对象(组件)配置到Spring中,交给Spring来创建管理;具体来说:将MyBatis匹配文件中的数据源、SQL映射文件、SqlSessionFactoryBu......
  • Python 类型注解
    在Python语言发展的过程中,PEP提案发挥了巨大的作用,如PEP3107和PEP484提案,分别给我们带来了函数注解(FunctionAnnotations)和类型提示(TypeHints)的功能。PEP3107:定义了......
  • 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第一件事,导入相关的包(注意版本,下面仅供参考)<!--代码生成器--><!--......