新建User,role,Permission三个实体类
User类
private Integer uId;
private String userName;
private String password;
private Set<Roles> role = new HashSet<Roles>();
Roles 类
private Integer rId;
private String name;
private Set<Permission> permissions = new HashSet<Permission>();
private Set<User> user = new HashSet<User>();
Permission类
private Integer pId;
private String name;
private String url;
其中user包含了role的集合,并且role包含了permission的集合
当我们想以user_name为关键字查询时,sql的写法
<resultMap type="User" id="userMap">
<id property="uId" column="id"/>
<result property="userName" column="userName" />
<result property="password" column="password"/>
<collection property="role" ofType="Roles">
<id property="rId" column="rId"/>
<result property="name" column="name"/>
<collection property="permissions" ofType="Permission">
<id property="pId" column="pId"/>
<result property="name" column="pName"/>
<result property="url" column="url"/>
</collection>
</collection>
</resultMap>
其中<collection property="role" ofType="Roles">中的role要和user实体类中private Set<Roles> role = new HashSet<Roles>(); 名称保持一致
ofType="Roles"表示对应的实体类
<select id="findByUserName" parameterType="String" resultMap="userMap">
select
a.id AS "id",
a.user_name AS "userName",
a.password AS "password",
r.id AS "rId",
r.name AS "name",
p.id AS "pId",
p.name AS "pName",
p.url AS "url"
from user a
inner join user_role ur on ur.uId = a.id
left join role r on r.id = ur.rId
left join permission_role pr on pr.rId = r.id
left join permission p on p.id = pr.pId
where a.user_name = #{0}
</select>
注意:sql中的别名要和column中的保持一致