我们在设计表的时候往往一个表的外键作为另一张表的主键,那么我们在查询的时候就要查询两个表的数据。
下面来说下实现的方法。
数据库表的结构
wc_user实体类
public class WcUser implements Serializable {
//用户id
private String userId;
//用户密码
private String userPassword;
//是否被锁定,0锁定,1没锁
private String userActive;
wc_user_roles实体类
public class WcUserRoles implements Serializable {
//用户id
private String userId;
//用户角色
private String userRole;
由于要连表查询所以我们还要创建一个表,只有把另一个类添加进来就好了。
public class WcUserAll {
private String userId;
private String userPassword;
private String userActive;
private WcUserRoles wcUserRoles;
public WcUserAll(String userId, String userPassword, String userActive) {
super();
this.userId = userId;
this.userPassword = userPassword;
this.userActive = userActive;
}
在WcUserMapper.xml写一个WcUserAll类的resultMap,然后使用左外连接(left join)就可以实现连表查询了
<resultMap id="WithRoleResultMap" type="com.smxy.wechat.pojo.WcUserAll">
<id column="user_id" property="userId" jdbcType="VARCHAR" />
<result column="user_password" property="userPassword"
jdbcType="VARCHAR" />
<result column="user_active" property="userActive" jdbcType="VARCHAR" />
<association property="wcUserRoles" javaType="com.smxy.wechat.pojo.WcUserRoles">
<id column="user_id" property="userId" jdbcType="VARCHAR" />
<result column="user_role" property="userRole" jdbcType="VARCHAR" />
</association>
</resultMap>
<select id="selectRoleByPrimaryKey" resultMap="WithRoleResultMap"
parameterType="java.lang.String">
select
<include refid="withRole_Column_List" />
from wc_user a
left join
wc_user_roles b on a.`user_id`=b.`user_id`
where a.user_id=#{userId,jdbcType=VARCHAR}
</select>
在Controller调用selectRoleByPrimaryKey该方法就可以查询了
查询结果如下图