例子是参考Mybatis文档创建的一个简单例子,一共涉及4个表,每个表都有很少的几个属性。
由于说明该内容需要东西太多,专门分成两篇文章,一篇提供表以及基础代码,一篇专门讲内容。
表如下:
Blog表
Blog_user表
Blog_post表
Blog_comments表
代码(其他对象不在这儿贴出来了,请需要的自己下载):
BlogMapper.java
public interface BlogMapper { BlogDto selectById(String id); }
<?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://blog.csdn.net/isea533/article/details/19821071