Mybatis 中一对多,以及多对一的案例详解

最近在整理笔记,就把mybaits 中一对多,以及多对一查询详细的捋一遍。

  1. 首先 准备sql 数据 user(用户表) account(账户表) 一个用户可以有多个账户,一个账户只属于一个用户;
  2. 建立maven 工程 导入相关依赖 ,mybatis,mysql,junit,log4j;
  3. 建立实体类User和Account;
  4. 编写Dao,以及映射文件和主配置文件,下面上代码
  5. 编写测试类

项目的结构为:

1)sql数据-----

/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.5.40 : Database - mybatis
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `mybatis`;

/*Table structure for table `account` */

DROP TABLE IF EXISTS `account`;

CREATE TABLE `account` (
  `ID` int(11) NOT NULL COMMENT '编号',
  `UID` int(11) DEFAULT NULL COMMENT '用户编号',
  `MONEY` double DEFAULT NULL COMMENT '金额',
  PRIMARY KEY (`ID`),
  KEY `FK_Reference_8` (`UID`),
  CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `account` */

insert  into `account`(`ID`,`UID`,`MONEY`) values (1,41,1000),(2,41,1000),(3,48,2000);

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` datetime DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8;

/*Data for the table `user` */

insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'11111','2018-02-27 17:47:08','男','北京'),(42,'小二王','2018-03-02 15:09:37','女','北京金燕龙'),(43,'小二王','2018-03-04 11:34:34','男','北京金燕龙'),(45,'传智播客','2018-03-04 12:04:06','男','北京金燕龙'),(48,'小马宝莉','2018-03-08 11:44:00','女','北京修正'),(54,'黄顺','2019-04-29 09:41:15','男','安徽');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

2)建立maven 工程导入相应依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.hs</groupId>
    <artifactId>mybatis_one_t_omore</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
</project>

3)创建实体类

user:
package domain;

import java.util.Date;
import java.util.List;

/**
 * @Author: huangshun
 * @Date: 2019/4/30 10:28
 * @Version 1.0
 */
public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    private List<Account> accounts;// 一对多 一个用户包含多个账户

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ", accounts=" + 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 Date getBirthday() {
        return birthday;
    }

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

    public String getSex() {
        return sex;
    }

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

    public String getAddress() {
        return address;
    }

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

Account:

package domain;

/**
 * @Author: huangshun
 * @Date: 2019/4/30 10:39
 * @Version 1.0
 */
public class Account {
    /**
     * 账户的实体类 一个用户对应 多个账户
     */
    private Integer id;
    private Integer uid;
    private double money;
    private User user;

    public User getUser() {
        return user;
    }

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

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                ", 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;
    }
}


4)编写dao

UserDao:
-----------------------------------------------------------------------------------------
package dao;

import domain.User;

import java.util.List;

/**
 * @Author: huangshun
 * @Date: 2019/4/30 10:31
 * @Version 1.0
 */
public interface UserDao {
    /**
     * 查询所有用户信息 包含用户的账户--
     * @return
     */
    List<User> findAll();
}

-----------------------------------------------------------------------------------------
AccountDao:


package dao;

import domain.Account;

import java.util.List;

/**操作账户的Dao
 * @Author: huangshun
 * @Date: 2019/4/30 10:42
 * @Version 1.0
 */

public interface AccountDao {
    /**
     * 查询所有账户的信息 包括账户所属于的用户  一对一的查询
     * @return
     */
    List<Account> findAllAccount();
}

编写配置文件

这里较为重要:

UserDaoMapping.xml
--------------------------------------------------------------------------------------

<?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="dao.UserDao">
    <resultMap id="userMap" type="domain.User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
        <result property="birthday" column="birthday"></result>

        <!--配置账户数据的集合 -->
        <collection property="accounts" ofType="domain.Account">
            <!--
             注意:
             这里colum="aid"为什么要这么写 因为上面user那边已经定义了一个id
             若这里再定义为id 就会把user的id 封装到account的id里,
             所以这里定义的为aid  同时sql语句里也要 a.id as aid
             理论上没变 属性对应 数据库字段名 只是现在字段是aid了
            -->

            <id property="id" column="aid"></id>
            <result property="uid" column="uid"></result>
            <result property="money" column="money"></result>
        </collection>
    </resultMap>
    <select id="findAll" resultMap="userMap">
        select u.*,a.id as aid,a.money from user u left join account a on u.id=a.uid;
    </select>
</mapper>

--------------------------------------------------------------------------------------

AccountDaoMapping.xml
-------------------------------------------------------------------------------------

<?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="dao.AccountDao">
    <resultMap id="accountMap" type="domain.Account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"/>
        <result property="money" column="money"/>

        <!-- 它是用于指定从表方的引用实体属性的
            property: 对应account实体类的user 属性
            javaType:指的是类型
        -->
        <association property="user" javaType="domain.User">
            <!--注意:
             这里colum="uid"为什么要这么写 因为上面账户那边已经定义了一个id
             若这里再定义为id 就会把账户的id 封装到user的id里,
             所以这里定义的为uid  同时sql语句里也要 u.id as uid
             理论上没变 属性对应 数据库字段名 只是现在字段是uid了
             -->

            <id property="id" column="uid"></id>
            <result property="username" column="username"></result>
            <result property="birthday" column="birthday"></result>
            <result property="sex" column="sex"></result>
            <result property="address" column="address"></result>
        </association>
    </resultMap>
    <!--查询所有账户信息 同时包括账户所属的联系人信息 -->
    <!--一对一 一个账户对应一个用户 -->
    <select id="findAllAccount" resultMap="accountMap">
        SELECT a.*,u.id as uid,u.username,u.address FROM account AS a,USER AS u WHERE a.uid=u.id;

        <!--select u.*,a.id as aid,a.uid,a.money from account a,user u where a.uid =u.id;-->
    </select>
</mapper>

--------------------------------------------------------------------------------------
SqlMapConfig.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">
<!-- mybatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
    <mappers>
        <mapper resource="UserDaoMapping.xml"/>
        <mapper resource="AccountDaoMapping.xml"></mapper>
    </mappers>
</configuration>

 

5)编写测试类

TestUser:
-----------------------------------------------------------------------------------------import dao.UserDao;
import 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.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Author: huangshun
 * @Date: 2019/4/30 10:34
 * @Version 1.0
 */
public class TestUser {
    InputStream in;
    SqlSession sqlSession;
    SqlSessionFactory factory;
    UserDao dao;


    @Before
    public void testBefore() throws IOException {
        in= Resources.getResourceAsStream("SqlMapConfig.xml");
        factory =new SqlSessionFactoryBuilder().build(in);
        sqlSession = factory.openSession();
        dao = sqlSession.getMapper(UserDao.class);
    }

    @After
    public void testAfter() throws IOException {
        sqlSession.close();
        in.close();

    }

    /**
     * 测试查询所有用户信息 一对多 一个用户可以包含多个账户
     */
    @Test
    public void testFindAll(){
        List<User> users = dao.findAll();
        for (User user : users) {
            System.out.println(user);
/*输出结果
User{id=41, username='11111', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', address='北京', accounts=[Account{id=1, uid=null, money=1000.0, user=null}, Account{id=2, uid=null, money=1000.0, user=null}]}
User{id=42, username='小二王', birthday=Fri Mar 02 15:09:37 CST 2018, sex='女', address='北京金燕龙', accounts=[]}
User{id=43, username='小二王', birthday=Sun Mar 04 11:34:34 CST 2018, sex='男', address='北京金燕龙', accounts=[]}
User{id=45, username='客', birthday=Sun Mar 04 12:04:06 CST 2018, sex='男', address='北京金燕龙', accounts=[]}
User{id=48, username='小马宝莉', birthday=Thu Mar 08 11:44:00 CST 2018, sex='女', address='北京修正', accounts=[Account{id=3, uid=null, money=2000.0, user=null}]}
User{id=54, username='黄顺', birthday=Mon Apr 29 09:41:15 CST 2019, sex='男', address='安徽', accounts=[]}
            * 
            * 
            * 
            * 
            * */
        }
    }
}


-----------------------------------------------------------------------------------------TestAccount:
import dao.AccountDao;
import dao.UserDao;
import domain.Account;
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.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Author: huangshun
 * @Date: 2019/4/30 11:06
 * @Version 1.0
 */
public class TestAccount {
    InputStream in;
    SqlSession sqlSession;
    SqlSessionFactory factory;
    AccountDao dao;


    @Before
    public void testBefore() throws IOException {
        in= Resources.getResourceAsStream("SqlMapConfig.xml");
        factory =new SqlSessionFactoryBuilder().build(in);
        sqlSession = factory.openSession();
        dao = sqlSession.getMapper(AccountDao.class);
    }

    @After
    public void testAfter() throws IOException {
        sqlSession.close();
        in.close();

    }

    /**
     * 查询所有账户的信息,同时包含用户信息 多对一(一对一)
     */
    @Test
    public void testfindAllAccount(){
        List<Account> accounts = dao.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
            /*测试结果:
Account{id=1, uid=41, money=1000.0, user=User{id=41, username='11111', birthday=null, sex='null', address='北京', accounts=null}}
Account{id=2, uid=41, money=1000.0, user=User{id=41, username='11111', birthday=null, sex='null', address='北京', accounts=null}}
Account{id=3, uid=48, money=2000.0, user=User{id=48, username='小马宝莉', birthday=null, sex='null', address='北京修正', accounts=null}}
            * 
            * */
        }

    }
}

至此,本案例结束

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值