前期准备见 Mybatis 多表间查询之 多对一
0.准备
1. domain Category
2. 主配置文件
...
</environments>
<mappers>
<mapper resource="cn/ccut/mapper/CategoryDao.xml" ></mapper>
</mappers>
</configuration>
3. 接口ICategoryDao
public interface ICategoryDao {
Category getCate(String cid);
}
1. 连接查询
1.1 映射配置文件 CategoryDao.xml
<?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="cn.ccut.dao.ICategoryDao">
<resultMap id="res1" type="cn.ccut.domain.Category">
<id property="cid" column="tcid"/>
<result property="cname" column="tcname"/>
<result property="desc" column="desc"/>
<collection property="bList" ofType="cn.ccut.domain.Book">
<id property="bid" column="bid"/>
<result property="bname" column="bname"/>
<result property="author" column="author"/>
<result property="price" column="price"/>
<result property="press" column="press"/>
<result property="cid" column="cid"/>
</collection>
</resultMap>
<select id="getCate" resultMap="res1">
select t1.cid tcid,t1.cname tcname,t1.desc,t.* from t_book t join t_category t1 on t.cid=t1.cid and t.cid=#{cid}
</select>
</mapper>
1.2 测试
public class tests {
@Test
public void fun(){
ICategoryDao mapper = MyBatisUtil.openSession().getMapper(ICategoryDao.class);
System.out.println( mapper.getCate("5F79D0D246AD4216AC04E9C5FAB3199E"));
}
}
成功
2. 分步查询
2.1 CategoryDao.xml
<?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="cn.ccut.dao.ICategoryDao">
<resultMap id="res1" type="cn.ccut.domain.Category">
<id property="cid" column="cid"/>
<collection property="bList" column="cid" ofType="cn.ccut.domain.Book" select="selectBook">
</collection>
</resultMap>
<select id="getCate" resultMap="res1">
select * from t_Category where cid=#{cid}
</select>
<select id="selectBook" resultType="cn.ccut.domain.Book">
select * from t_book where cid=#{c1id}
</select>
</mapper>