1、数据库表
CREATE TABLE `country` ( `cid` int(4) NOT NULL AUTO_INCREMENT COMMENT '国家id', `cname` varchar(20) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`cid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;CREATE TABLE `provincial` ( `pid` int(4) NOT NULL AUTO_INCREMENT, `pname` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `countryid` int(4) NOT NULL, PRIMARY KEY (`pid`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
2、实体类
package cn.bdqn.bean;/** *国家的实体类 */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; } public Country(Integer cId, String cName) { super(); this.cId = cId; this.cName = cName; } public Country() { super(); } @Override public String toString() { return "Country [cId=" + cId + ", cName=" + cName; }}
package cn.bdqn.bean;/** * *省会对应的实体类 */public class Provincial { private Integer pId; // 省会的编号 private String pName; // 省会名称 // 关联的国家属性 private Country country; public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public Integer getpId() { return pId; } public void setpId(Integer pId) { this.pId = pId; } public String getpName() { return pName; } public void setpName(String pName) { this.pName = pName; } public Provincial(Integer pId, String pName) { super(); this.pId = pId; this.pName = pName; } public Provincial() { super(); } /*@Override public String toString() { return "Provincial [pId=" + pId + ", pName=" + pName + ", country=" + country + "]"; }*/}
3、mybatis.xml配置文件
4、Dao层接口
package cn.bdqn.dao;import cn.bdqn.bean.Provincial;public interface ProvincialDao { /** * 根据省会的id查询出省会和对应国家的信息 */ Provincial selectProvincialById(Integer pId);}
5、Mapper.xml
6、测试类
package cn.bdqn.test;import org.apache.ibatis.session.SqlSession;import org.apache.log4j.Logger;import org.junit.After;import org.junit.Before;import org.junit.Test;import cn.bdqn.bean.Provincial;import cn.bdqn.dao.ProvincialDao;import cn.bdqn.util.MybatisUtil;public class Test1 { private Logger logger = Logger.getLogger(Test1.class); SqlSession session; ProvincialDao dao; @Before public void before() { // 因为需要关闭session 需要把session提取出去 session = MybatisUtil.getSqlSession(); dao = session.getMapper(ProvincialDao.class); } @After public void after() { if (session != null) { session.close(); } } @Test public void test1() { Provincial provincial = dao.selectProvincialById(1); /*logger.debug("provincialId=1======>provincial:" + provincial);*/ /*logger.debug("provincialId=1======>country:" + provincial.getCountry());*/ }}