1.联表查询
xml文件编写格式如下(mapper/CommunityMapper.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.system.mapper.CommunityMapper">
<select id="loadCommunityByAuthorId" parameterType="int" resultMap="loadCommunityWithAuthor">
select
Community.id as c_id,
Community.communityName as c_communityName,
Community.imageUrl as c_imageUrl,
Community.userId as c_userId,
User.id as u_id,
User.userAccount as u_userAccount,
User.userName as u_userName,
User.imageUrl as u_imageUrl,
User.userType as u_userType,
User.createTime as u_createTime,
User.sex as u_sex
from Community left join User on Community.userId = User.id where User.id = ${userId} <!-- 后面发现这个参数名这里填什么都无所谓,能映射到 -->
</select>
<resultMap id="loadCommunityWithAuthor" type="com.system.beans.Community">
<id property="id" column="c_id" />
<result property="communityName" column="c_communityName"/>
<result property="imageUrl" column="c_imageUrl"/>
<association property="user" javaType="com.system.beans.User">
<id property="id" column="u_id"/>
<result property="userAccount" column="u_userAccount"/>
<result property="userName" column="u_userName"/>
<result property="imageUrl" column="u_imageUrl"/>
<result property="userType" column="u_userType"/>
<result property="createTime" column="u_createTime"/>
<result property="sex" column="u_sex"/>
</association>
</resultMap>
</mapper>
Enity类(对命名没有要求)
@Expose private long id;
@Expose private String communityName;
@Expose private String imageUrl;
@Expose private Timestamp createTime;
@Expose private long userId;
@Expose private String note;
@Expose private int state;
@Expose private User user;
Mapper Interface(mapper/CommunityMapper.java)
package com.system.mapper;
import com.system.beans.Community;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface CommunityMapper {
List<Community> loadCommunityByAuthorId(@Param("userId") long userId);
}