注:代碼已託管在GitHub
上,地址是:https://github.com/Damaer/Mybatis-Learning
,項目是mybatis-12-many2one
,須要自取,須要配置maven
環境以及mysql
環境(sql
語句在resource
下的test.sql
中),以爲有用能夠點個小星星。java
docsify
文檔地址在:https://damaer.github.io/Mybatis-Learning/#/
mysql
一對多關聯查詢:每一個國家有不少大臣,領導人,如今咱們查詢一個領導,但願能將他所在國家的信息連帶出來,這就是一對多關聯查詢。git
數據表以下:
國家表:
github
領導人表:
sql
#建立數據庫 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
類:shell
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 + '}'; } }
Mybatis
工具類,獲取sqlsession
實例:session
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
文件:mybatis
<mappers> <mapper resource="mapper/mapper.xml"/> </mappers>
接口的聲明:app
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'}}
【做者簡介】:
秦懷,公衆號【秦懷雜貨店】做者,技術之路不在一時,山高水長,縱使緩慢,馳而不息。這個世界但願一切都很快,更快,可是我但願本身能走好每一步,寫好每一篇文章,期待和大家一塊兒交流。