1. 程式人生 > >(十六)mybatis多對一關聯查詢

(十六)mybatis多對一關聯查詢

注:程式碼已託管在GitHub上,地址是:https://github.com/Damaer/Mybatis-Learning ,專案是mybatis-12-many2one,需要自取,需要配置maven環境以及mysql環境(sql語句在resource下的test.sql中),覺得有用可以點個小星星,小菜鳥在此Thanks~
一對多關聯查詢:每個國家有很多大臣,領導人,現在我們查詢一個領導,希望能將他所在國家的資訊連帶出來,這就是一對多關聯查詢。
資料表如下:



建立資料庫/表

#建立資料庫
CREATE DATABASE `test` DEFAULT CHARACTER
SET utf8 COLLATE utf8_general_ci;
#建立資料表 CREATE TABLE `test`.`country` ( `cid` INT(10) NOT NULL AUTO_INCREMENT ,`cname` VARCHAR(20) NOT NULL ,PRIMARY KEY(`cid`)) ENGINE = MyISAM; CREATE TABLE `test`.`minister` ( `mid` INT(10) NOT NULL AUTO_INCREMENT ,`mname` VARCHAR(20) NOT NULL ,`countryId` INT(20) NOT
NULL ,PRIMARY KEY(`mid`)) ENGINE = MyISAM;
#初始化資料表 INSERT INTO `country` (`cid`, `cname`) VALUES ('1', 'USA'); INSERT INTO `country` (`cid`, `cname`) VALUES ('2', 'England'); INSERT INTO `minister` (`mid`, `mname`, `countryId`) VALUES ('1', 'aaa', '1'); INSERT INTO `minister` (`mid`, `mname`, `countryId`
) VALUES ('2', 'bbb', '1');
INSERT INTO `minister` (`mid`, `mname`, `countryId`) VALUES ('3', 'ccc', '2'); INSERT INTO `minister` (`mid`, `mname`, `countryId`) VALUES ('4', 'ddd', '2'); INSERT INTO `minister` (`mid`, `mname`, `countryId`) VALUES ('5', 'eee', '2');

實體類

country類:

public class Country {
    private Integer cid;
    private String cname;

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        return "Country{" +
                        "cid=" + cid +
                        ", cname='" + cname + '\'' +
                        '}';
    }
}

minister類,在這個類裡面使用country當屬性。

public class Minister {
    private Integer mid;
    private String mname;
    private Country country;

    public Integer getMid() {
        return mid;
    }

    public void setMid(Integer mid) {
        this.mid = mid;
    }

    public String getMname() {
        return mname;
    }

    public void setMname(String mname) {
        this.mname = mname;
    }

    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return "Minister{" +
                        "mid=" + mid +
                        ", mname='" + mname + '\'' +
                        ", country=" + country +
                        '}';
    }
}

工具類,獲取sqlsession例項:

public class MyBatisUtils {

    /*  public SqlSession getSqlSession(){
            InputStream is;
            try {
                is = Resources.getResourceAsStream("mybatis.xml");
                return new SqlSessionFactoryBuilder().build(is).openSession();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }*/
    static private SqlSessionFactory sqlSessionFactory;

    static public SqlSession getSqlSession() {
        InputStream is;
        try {
            is = Resources.getResourceAsStream("mybatis.xml");
            if (sqlSessionFactory == null) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            }
            return sqlSessionFactory.openSession();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

在mybatis.xml主配置檔案裡面註冊mapper檔案:

<mappers>
    <mapper resource="mapper/mapper.xml"/>
</mappers>

介面的宣告:

public interface IMinisterDao {
    Minister selectMinisterById(int mid);
    Minister selectMinisterById2(int mid);
}

mapper檔案最重要的部分,與一對一有點像,兩種查詢方式,一種是巢狀結果,一種是巢狀查詢,巢狀查詢可以使用懶載入模式,比較常用:

<?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.IMinisterDao">
<!--    resultMap 能解決欄位和屬性不一樣的問題 -->
    <!-- 以後用得比較多 ,是因為可以使用延遲載入-->
    <!-- 巢狀查詢 -->
    <select id="selectCountryById" resultType="Country">
    select * from country where cid=#{countryId}
    </select>
    <resultMap type="Minister" id="countryMapper">
        <id column="mid" property="mid"/>
        <result column="mname" property="mname"/>
        <!-- country中有一個成員變數是ministers,它的泛型是Minister -->
        <collection property="country"
                    ofType="Country"
                    select="selectCountryById"
                    column="countryId">
        </collection>
    </resultMap>
    <select id="selectMinisterById" resultMap="countryMapper">
        select mid,mname,countryId
        from minister
        where 
        mid=#{mid}
    </select>

    <!-- 巢狀結果-->
    <select id="selectMinisterById2" resultMap="countryMapper2">
        select mid,mname,countryId,cid,cname
        from minister,country
        where
        mid=#{mid} and countryId = cid
    </select>
    <resultMap id="countryMapper2" type="Minister">
        <id column="mid" property="mid"/>
        <result column="mname" property="mname"/>
        <collection property="country" ofType="Country">
            <id property="cid" column="cid"/>
            <result property="cname" column="cname"/>
        </collection>
    </resultMap>
</mapper>

單元測試:

public class MyTest {
  private IMinisterDao dao;
  private SqlSession sqlSession;
  @Before
  public void Before(){
    sqlSession=MyBatisUtils.getSqlSession();
    dao=sqlSession.getMapper(IMinisterDao.class);
  }
  @Test
  public void TestselectMinisterById(){
    Minister minister = dao.selectMinisterById(1);
    System.out.println(minister);
  }

  @Test
  public void TestselectMinisterById2(){
    Minister minister = dao.selectMinisterById2(1);
    System.out.println(minister);
  }


  @After
  public void after(){
    if(sqlSession!=null){
      sqlSession.close();
    }
  }

}

結果:

[service] 2018-07-12 20:07:23,875 - dao.IMinisterDao.selectMinisterById2 -567  [main] DEBUG dao.IMinisterDao.selectMinisterById2  - ==>  Preparing: select mid,mname,countryId,cid,cname from minister,country where mid=? and countryId = cid 
[service] 2018-07-12 20:07:23,909 - dao.IMinisterDao.selectMinisterById2 -601  [main] DEBUG dao.IMinisterDao.selectMinisterById2  - ==> Parameters: 1(Integer)
[service] 2018-07-12 20:07:23,930 - dao.IMinisterDao.selectMinisterById2 -622  [main] DEBUG dao.IMinisterDao.selectMinisterById2  - <==      Total: 1
Minister{mid=1, mname='aaa', country=Country{cid=1, cname='USA'}}