我在mybatis中遇到了一些问题。这是我的配置:
PostMapper.xml
<mapper namespace="com.king.model.PostMapper">
<select id="selectById" parameterType="int" resultMap="postMap">
select * from posts where id = #{id}
</select>
<select id="selectAll" resultType="hashmap">
select * from posts order by created_at desc
</select>
<resultMap id="postMap" type="Post">
<result property="createDate" column="created_at" />
<result property="updateDate" column="updated_at" />
</resultMap>
</mapper>
评论映射器.xml
<mapper namespace="com.king.model.CommentMapper">
<select id="selectById" parameterType="int" resultMap="commentMap">
select * from comments where id = #{id} order by id desc
</select>
<select id="selectAll" resultMap="commentMap">
select * from comments
</select>
<select id="selectByPost" resultMap="commentMap" parameterType="int">
select * from comments where post_id=#{id}
</select>
<resultMap id="commentMap" type="Comment">
<result property="createDate" column="created_at" />
<result property="updateDate" column="updated_at" />
<association property="post" column="post_id" javaType="Post" select="com.king.model.PostMapper.selectById" />
</resultMap>
</mapper>
public class Post {
private int id;
private String title;
private String body;
private Date createDate;
private Date updateDate;
private List<Comment> comments;
}
public class Comment {
private int id;
private String commenter;
private String body;
private Post post;
private Date createDate;
private Date updateDate;
}
在 CommentDao 中:
public List<Comment> listForPost(Post post) {
return getSqlSession().selectList("com.king.model.CommentMapper.selectByPost", post.getId());
}
然后在我的控制器中,我尝试列出给定帖子的所有评论:
List<Comment> coms = commentDao.listForPost(post);
post.setComments(coms)
而且我发现上面的代码会触发两条sql select语句:
select * from comments where post_id=?
select * from posts where id = ?
但是通过mybatis 3指南,它指定在这个套装中,它会导致“N + 1”问题。
对于每个选定的评论,它会触发选择语句以获取详细信息(帖子)。
但这里只有两个选择。
这是怎么回事?
而在mybatis中,对于一对多或多对多关联,关系应该设置为双向还是单向?