++注:代碼已託管在GitHub上,地址是:https://github.com/Damaer/Mybatis-Learning
,項目是mybatis-10-one2many
,須要自取,須要配置maven
環境以及mysql
環境(sql
語句在resource
下的test.sql
中),以爲有用能夠點個小星。java
docsify
文檔地址在:https://damaer.github.io/Mybatis-Learning/#/
mysql
不少時候,當查詢條件涉及到具備關聯關係的多個表的時候,須要使用到關聯查詢,關聯查詢通常有四種。git
下面咱們須要實踐的是一對多關聯查詢,所謂一對多就是一個對象裏面的屬性是一個對象的集合。好比每一個國家都有幾個領導。對應的國家表以及領導人的表。github
#建立數據庫 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
對應的實體類,屬性有:cid
,cname
,以及miniters
,實現get()
以及set()
方法,tostring()
方法:sql
import java.util.Set; public class Country { private Integer cid; private String cname; private Set<Minister> ministers; public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } public String getName() { return cname; } public void setName(String cname) { this.cname = cname; } public Set<Minister> getMinisters() { return ministers; } public void setMinisters(Set<Minister> ministers) { this.ministers = ministers; } @Override public String toString() { return "Country [cid=" + cid + ", cname=" + cname + ", ministers=" + ministers + "]"; } }
Minister
的實體類,也須要實現set()
以及get()
方法,toString()
方法:shell
public class Minister { private Integer mid; private String mname; @Override public String toString() { return "Minister [mid=" + mid + ", mname=" + mname + "]"; } 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; } }
在mybatis.xml
文件裏面註冊mapper
文件:數據庫
<!-- 註冊映射文件 --> <mappers> <mapper resource="mapper/mapper.xml"/> </mappers>
咱們操做數據庫的接口:apache
public interface ICountryDao { Country selectCountryById(int cid); Country selectCountryById2(int cid); }
mapper.xml
文件,對應的兩種方式實現一對多查詢:mybatis
select
語句,可是這個語句只選出country
的信息,在resultMap
裏面自定義,包括一個<collection></collection>
,在裏面指定對應的類型,property
是屬性的名字,ofType
是這個屬所對應的類型,select
指定調用的另外一個select
語句,column
是傳進去的參數,這樣的方式能夠實現延遲加載,也就是用不到的時候,不會調用裏面的SQL
。這中多表單獨查詢能夠跨多個mapper
文件,只要寫上對應的namespace
就能夠了select
語句,與上面不同的是,這個select
語句將兩張表的字段都選擇出來了,咱們須要指定一個resultMap
,其餘子標籤同樣,可是<collection></collection>
裏面再也不調用另外的sql
語句,只是指定了屬性與字段對應就能夠了。<?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.ICountryDao"> <!-- resultMap 能解決字段和屬性不同的問題 --> <!-- 之後用得比較多 ,是由於能夠使用延遲加載--> <!-- 嵌套查詢 --> <select id="selectMinisterByCountry" resultType="Minister"> select mid,mname from minister where countryId=#{ooo} </select> <resultMap type="Country" id="countryMapper"> <id column="cid" property="cid"/> <result column="cname" property="cname"/> <!-- country中有一個成員變量是ministers,它的泛型是Minister --> <collection property="ministers" ofType="Minister" select="selectMinisterByCountry" column="cid"> </collection> </resultMap> <select id="selectCountryById" resultMap="countryMapper"> select cid,cname from country where cid=#{cid} </select> <!-- 嵌套結果--> <select id="selectCountryById2" resultMap="countryMapper2"> select * from country c,minister m where c.cid = m.countryId and c.cid= #{cid} </select> <resultMap id="countryMapper2" type="Country"> <id column="cid" property="cid"/> <result column="cname" property="cname"/> <collection property="ministers" ofType="Minister"> <id property="mid" column="mid"/> <result property="mname" column="mname"/> </collection> </resultMap> </mapper>
測試test:app
public class MyTest { private ICountryDao dao; private SqlSession sqlSession; @Before public void Before(){ sqlSession=MyBatisUtils.getSqlSession(); dao=sqlSession.getMapper(ICountryDao.class); } @Test public void TestselectCountryById(){ Country country=dao.selectCountryById(1); System.out.println(country); } @Test public void TestselectCountryById2(){ Country country=dao.selectCountryById2(1); System.out.println(country); } @After public void after(){ if(sqlSession!=null){ sqlSession.close(); } } }
使用到的工具類:MybatisUtils.java
public class MyBatisUtils { 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; } }
兩個接口的結果一致:
[service] 2018-07-12 14:01:15,835 - org.apache.ibatis.transaction.jdbc.JdbcTransaction -508 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4abdb505] [service] 2018-07-12 14:01:15,837 - dao.ICountryDao.selectCountryById2 -510 [main] DEBUG dao.ICountryDao.selectCountryById2 - ==> Preparing: select * from country c,minister m where c.cid = m.countryId and c.cid= ? [service] 2018-07-12 14:01:15,869 - dao.ICountryDao.selectCountryById2 -542 [main] DEBUG dao.ICountryDao.selectCountryById2 - ==> Parameters: 1(Integer) [service] 2018-07-12 14:01:15,884 - dao.ICountryDao.selectCountryById2 -557 [main] DEBUG dao.ICountryDao.selectCountryById2 - <== Total: 2 Country [cid=1, cname=USA, ministers=[Minister [mid=2, mname=bbb], Minister [mid=1, mname=aaa]]]
【做者簡介】:
秦懷,公衆號【秦懷雜貨店】做者,技術之路不在一時,山高水長,縱使緩慢,馳而不息。這個世界但願一切都很快,更快,可是我但願本身能走好每一步,寫好每一篇文章,期待和大家一塊兒交流。