MyBatis(16)- Mybatis多表操作

1 表之間的關係

  1. 一對多:用戶和訂單
  2. 多對一:訂單和用戶
  3. 一對一:一個人一個身份證號
  4. 多對多:一個學生可以選多門課,每門課可以被多名學生選

2 建立 account 表

案例: 用戶和賬戶

  • 一個用戶可以有多個賬戶
  • 一個賬戶只能屬於一個用戶(多個賬戶也可以屬於同一個用戶)

步驟:

  1. 建立兩張表:用戶表、賬戶表。在賬戶表添加外鍵
  2. 建立兩個實體類:用戶類和賬戶類。
  3. 建立2個配置文件
  4. 實現配置:當查詢用戶時,可以同時得到用戶下所包含的賬戶信息。查詢賬戶時,可以同時得到賬戶所屬用戶信息。

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 DEFAULT CHARSET=utf8;
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;

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

在這裏插入圖片描述
在這裏插入圖片描述

3 一對一 【通過子類實現】

通過寫 Account 子類實現


3.1 實體類

  • Account
    在這裏插入圖片描述

  • User
    在這裏插入圖片描述

  • AccountUser

package com.tzb.domain;

public class AccountUser extends Account {

    private String username;

    private String address;

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

    @Override
    public String toString() {
        return super.toString()+ " AccountUser{" +
                "username='" + username + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

3.2 DAO

  • IUserDao
package com.tzb.dao;

import com.tzb.domain.User;


import java.util.List;

public interface IUserDao {
    List<User> findAll();

    User findById(Integer userId);

}

  • IUserDao.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="com.tzb.dao.IUserDao">

    <!--配置查詢所有-->
    <select id="findAll" resultType="user">
       select * from user
    </select>
    
    <select id="findById" parameterType="int" resultType="com.tzb.domain.User">
    select * from user where id=#{userId}

    </select>
    
</mapper>

  • IAccountDao
package com.tzb.dao;

import com.tzb.domain.Account;
import com.tzb.domain.AccountUser;

import java.util.List;

public interface IAccountDao {

    List<Account> findAll();

    /**
     * 查詢所有賬戶,並帶有用戶名稱和地址信息
     * @return
     */
    List<AccountUser> findAllAccount();


}
  • IAccountDao.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="com.tzb.dao.IAccountDao">

    <select id="findAll" resultType="Account">
       select * from account
    </select>

    <!--查詢所有賬戶,同時包含用戶名和地址信息-->
    <select id="findAllAccount" resultType="AccountUser">
        select a.*,u.username,u.address
        from account a,user u
        where u.id = a.uid
    </select>

</mapper>

3.3 MyBatis配置文件 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>

    <properties resource="jdbc.properties"></properties>

    <!--配置別名,配置 domain 類中的別名
        配置了別名後,就不在區分大小寫
    -->
    <typeAliases>
        <!--該包下所有的實體類都被註冊別名,類名就是別名,不在區分大小寫-->
        <package name="com.tzb.domain"/>
    </typeAliases>

    <!--配置環境-->
    <environments default="mysql">
        <environment id="mysql">
            <!--配置事務類型-->
            <transactionManager type="JDBC"></transactionManager>

            <!--配置數據源(連接池)-->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--指定dao接口所在的包,不需要再寫 mapper 以及resource或者 class-->
    <mappers>
        <package name="com.tzb.dao"/>
    </mappers>

</configuration>

3.4 單元測試

public class AccountTest {

    private InputStream in;
    private SqlSession sqlSession;
    private IAccountDao accountDao;

    @Before
    public void init() throws IOException {
        // 1.讀取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");

        //2.創建 SqlSessionFactory 工廠
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

        // 3.使用工廠生產 SqlSession 對象
        sqlSession = factory.openSession();

        // 4.使用 SqlSession 創建DAO接口的代理對象
        accountDao = sqlSession.getMapper(IAccountDao.class);
    }

    @After
    public void destory() throws IOException {

        // 提交事務
        sqlSession.commit();

        //6.釋放資源
        sqlSession.close();
        in.close();
    }


    @Test
    public void testFindAll() throws IOException {
       List<Account> accounts = accountDao.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindAllAccountUser() throws IOException {
        List<AccountUser> aus = accountDao.findAllAccount();
        for (AccountUser au : aus) {
            System.out.println(au);
        }
    }
    
}

在這裏插入圖片描述

4 一對一操作【建立實體類關係操作】

在這裏插入圖片描述

  • IAccountDao.xml
<resultMap id="accountUserMap" type="account">
        <id property="id" column="aid"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>

        <!--一對一的關係映射,配置封裝 user 的內容
            column:通過哪一個字段獲取
        -->
        <association property="user" column="uid" javaType="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>
        </association>
    </resultMap>

    <select id="findAll" resultMap="accountUserMap">
       select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id=a.uid
    </select>
  • 單元測試
 @Test
    public void testFindAll() throws IOException {
       List<Account> accounts = accountDao.findAll();
        for (Account account : accounts) {
            System.out.println("--- 每個 Account 的內容-----");
            System.out.println(account);
            System.out.println(account.getUser());
            System.out.println("============================");
        }
    }

在這裏插入圖片描述


Google開發專家帶你學 AI:入門到實戰(Keras/Tensorflow)(附源碼)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章