实现关联数据的查询
1 创建数据源
#创建表article
Drop TABLE IF EXISTS `article`;
Create TABLE `article` (
`id` int(11) NOT NULL auto_increment,
`userid` int(11) NOT NULL,
`title` varchar(100) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- 添加几条测试数据
-- ----------------------------
Insert INTO `article` VALUES ('1', '1', 'test_title', 'test_content');
Insert INTO `article` VALUES ('2', '1', 'test_title_2', 'test_content_2');
Insert INTO `article` VALUES ('3', '1', 'test_title_3', 'test_content_3');
Insert INTO `article` VALUES ('4', '1', 'test_title_4', 'test_content_4');
2 实体
public class Article {
/* id */
private int id;
/* 作者 */
private User user;
/* 标题 */
private String title;
/* 内容 */
private String content;
getter/setter..
}
3 修改user.xml
<!--文章article -->
<resultMap id="resultUserArticleList" type="cn.yue.mybatis.model.Article">
<id property="id" column="aid" />
<result property="title" column="title" />
<result property="content" column="content" />
<association property="user" javaType="cn.yue.mybatis.model.User">
<id property="id" column="id" />
<result property="userName" column="userName" />
<result property="userAddress" column="userAddress" />
</association>
</resultMap>
<!-- 根据用户id查询论文 -->
<select id="getUserArticles" parameterType="int"
resultMap="resultUserArticleList">
select
user.id,user.userName,user.userAddress,article.id
aid,article.title,article.content from user,article
where
user.id=article.userid and user.id=#{id}
</select>
4 测试
/**
* 根据用户id查询文章
*
* @param id
*/
public static void getUserArticles(int userId) {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation = session.getMapper(IUserOperation.class);
List<Article> articles = userOperation.getUserArticles(userId);
for (Article article : articles) {
System.out.println(article.getTitle() + ":" + article.getContent() + ":作者是:" + article.getUser().getUserName() + ":地址:" + article.getUser().getUserAddress());
}
} finally {
session.close();
}
}
参考:http://blog.csdn.net/techbirds_bao/article/details/9233599/