Mybatis嵌套查询讲解内容的基础

版权声明:版权归博主所有,转载请带上本文链接!联系方式:abel533@gmail.com https://blog.csdn.net/isea533/article/details/19821071

例子是参考Mybatis文档创建的一个简单例子,一共涉及4个表,每个表都有很少的几个属性。

由于说明该内容需要东西太多,专门分成两篇文章,一篇提供表以及基础代码,一篇专门讲内容。


表如下:

Blog表



Blog_user表



Blog_post表



Blog_comments表



代码(其他对象不在这儿贴出来了,请需要的自己下载):

BlogMapper.java

public interface BlogMapper {
    BlogDto selectById(String id);
}

BlogMapper.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="com.easternie.records.dao.BlogMapper" >
  <resultMap id="userMap" type="com.easternie.records.vo.model.BlogUser">
  	<id property="userid" column="userid"/>
	<result property="username" column="username" />
	<result property="password" column="password" />
	<result property="userinfo" column="userinfo" />
  </resultMap>
  
  <resultMap id="BlogDtoMap" type="com.easternie.records.vo.model.BlogDto">
  	<constructor>
		<idArg column="id" javaType="String"/>  	
  	</constructor>
  	<result property="title" column="title" />
  	<result property="url" column="url" />
  	<result property="userid" column="userid" />
  	<association property="user" resultMap="userMap" />
  	<collection property="posts" ofType="com.easternie.records.vo.model.BlogPostDto">
  		<id property="postid" column="postid" />
  		<!-- <result property="userid" column="userid" /> -->
  		<result property="postdate" column="postdate" />
  		<result property="postinfo" column="postinfo" />
  		<association property="user" resultMap="userMap"/>
  		<collection property="comments" ofType="com.easternie.records.vo.model.BlogComments">
  			<id property="commentid" column="commentid" />
  			<result property="username" column="username2"/>
  			<result property="msg" column="msg"/>
  		</collection>
  	</collection>
  </resultMap>
  
  <select id="selectById" resultMap="BlogDtoMap" parameterType="java.lang.String" >
    select a.id,
       a.title,
       a.userid,
       a.url,
       b.username,
       b.password,
       b.userinfo,
       c.postid,
       c.postdate,
       c.postinfo,
       d.commentid,
       d.username username2,
       d.msg
  from blog a

  left join blog_user b
    on a.userid = b.userid

  left join blog_post c
    on a.userid = c.userid

  left join blog_comments d
    on c.postid = d.postid
 where id = #{id}
  </select>
</mapper>

调用代码:

MyBatis myBatis = MyBatis.getInstance();
		try {
			SqlSessionFactory sessionFactory = myBatis.getSqlSessionFactory();
			SqlSession session = sessionFactory.openSession();
			BlogMapper blogMapper = session.getMapper(BlogMapper.class);
			BlogDto blogDto = blogMapper.selectById("1");
			show(blogDto);
		} catch (Exception e) {
			e.printStackTrace();
		}


下载地址:http://pan.baidu.com/s/1kT7HLdl
阅读更多

扫码向博主提问

isea533

博客专家

MyBatis相关答疑
  • 擅长领域:
  • MyBatis
  • Spring Boo
  • Spring
去开通我的Chat快问
换一批

没有更多推荐了,返回首页