1. 程式人生 > 實用技巧 >mybatis一對多查詢

mybatis一對多查詢

mybatis一對多查詢

需求:查詢所有使用者資訊及使用者關聯的賬戶資訊。

分析:使用者資訊和他的賬戶資訊為一對多關係,並且查詢過程中如果使用者沒有賬戶資訊,此時也要將使用者資訊查詢出來,我們想到了左外連線查詢比較合適

1、編寫sql語句

SELECT * FROM USER u LEFT OUTER JOIN account a ON u.`id`=a.`UID`

2、使用者實體類

package com.yl.bean;

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

/**
 * 使用者實體類
 */
public class User implements Serializable {
    private Integer id;//id
    private String username;//使用者名稱
    private Date birthday;//生日
    private String sex;//性別
    private String address;//地址
    private List<Account> accountList;//使用者所擁有的賬戶

    public User() {
    }

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

    public List<Account> getAccountList() {
        return accountList;
    }

    public void setAccountList(List<Account> accountList) {
        this.accountList = accountList;
    }

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

3、賬戶實體類

package com.yl.bean;

import java.io.Serializable;

/**
 * 賬戶實體類
 */
public class Account implements Serializable {
    private Integer id;//賬戶id
    private Integer uid;//使用者id
    private Double money;//餘額
    private User user;//賬戶所屬使用者

    public Account() {
    }

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

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

4、使用者持久層介面

package com.yl.dao;

import com.yl.bean.User;

import java.util.List;

/**
 * 使用者持久層介面
 */
public interface IUserDao {

    /**
     * 查詢所有使用者
     */
    List<User> queryAll();
}

5、使用者配置檔案

<?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.yl.dao.IUserDao">
    <!--配置使用者實體類和資料庫的對應資訊-->
    <resultMap id="userMap" type="com.yl.bean.User">
        <id property="id" column="id"></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>
        <!--一對多對映關係-->
        <collection property="accountList" ofType="com.yl.bean.Account">
            <id property="id" column="id"></id>
            <result property="uid" column="uid"></result>
            <result property="money" column="money"></result>
        </collection>
    </resultMap>

    <!--查詢所有使用者-->
    <select id="queryAll" resultMap="userMap">
        SELECT * FROM USER u LEFT OUTER JOIN account a ON u.`id`=a.`UID`
    </select>
</mapper>

6、測試

package com.yl;

import com.yl.bean.User;
import com.yl.dao.IUserDao;
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.sql.Date;
import java.util.List;


public class UserTest {
    private InputStream inputStream;
    private IUserDao userDao;
    private SqlSession sqlSession;

    @Before
    public void init() throws IOException {
        //讀取配置檔案
        inputStream= Resources.getResourceAsStream("SqlMapperConfig.xml");
        //建立工廠
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory= factoryBuilder.build(inputStream);
        //建立SqlSession物件
        sqlSession=sessionFactory.openSession();
        //建立IUserDao介面代理物件
        userDao=sqlSession.getMapper(IUserDao.class);
    }

    @After
    public void after() throws IOException {
        //提交事務
        sqlSession.commit();;
        //關閉資源
        sqlSession.close();
        inputStream.close();
    }

    /**
     * 查詢所有
     */
    @Test
    public void test01() throws IOException {
        //查詢所有使用者
        List<User> userList=userDao.queryAll();
        //遍歷輸出
        for (User user:userList){
            System.out.println(user);
            System.out.println(user.getAccountList());
        }
    }

}