场景:查询中间表对应的用户和角色,这里一条中间表数据分别只对应一个用户和一个角色。当然一般不会有这样的需求,这里只是举例一对一关系.
一、数据结构
1、用户表
2、角色表
3、中间表
二、xml自定义sql
<resultMap type="com.xiao.permission_system.entity.UerRole" id="BaseColumn">
<id column="id" property="id" />
<result column="uid" property="uid" />
<result column="role_id" property="roleId" />
<association property="users" javaType="com.xiao.permission_system.entity.UserInfo">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
</association>
<association property="roles" javaType="com.xiao.permission_system.entity.Role">
<id column="id" property="id" />
<result column="name" property="name" />
</association>
</resultMap>
<sql id="base">
ur.uid,
ur.role_id
</sql>
<sql id="userColumn">
u.id,
u.username,
u.password
</sql>
<sql id="roleColumn">
r.id,
r.name
</sql>
<select id="getRoles" resultMap="BaseColumn">
select
<include refid="base" />,
<include refid="userColumn" />,
<include refid="roleColumn" />
from sys_uer_role ur
LEFT JOIN sys_user_info u on u.id=ur.uid
LEFT join sys_role r on
r.id=ur.role_id
where
uid=#{uid}
</select>
三、中间表实体
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("sys_uer_role")
public class UerRole extends BaseEntity{
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId()
private String id;
private String uid;
private String roleId;
private UserInfo users;
private Role roles;
}