1.定义四个实体。User Role Privilege Resource,他们之间的对于关系为
2.需求:我通过用户名username查找出该用户对应的角色以及角色对应的权限和资源
3.实体
public class User implements Serializable { private String id; private String username; private String password; private Set<Role> role = new HashSet<Role>();
public class Role implements Serializable { private String id; private String name; private String des; private Set<Privilege> privilege = new HashSet<Privilege>();
public class Privilege implements Serializable { private String id; private String name; private String des;
private Set<Resource> resource = new HashSet<Resource>(); private Privilege parent; private Set<Privilege> child = new HashSet<Privilege>();
public class Resource implements Serializable { private String id; private String uri; private String des;
4.UserMapper.xml的查询方法为
<resultMap type="user" id="userResult"> <id column="id" property="id"/> <result column="username" property="username"/> <collection property="role" javaType="java.util.Set" resultMap="roleResult"/> </resultMap> <resultMap type="role" id="roleResult"> <id column="rid" property="id"/> <result column="rname" property="name"/> <result column="rdes" property="des"/> <collection property="privilege" javaType="java.util.Set" resultMap="privilegeResult"/> </resultMap> <resultMap type="privilege" id="privilegeResult"> <id column="pid" property="id"/> <result column="pname" property="name"/> <collection property="resource" javaType="java.util.Set" resultMap="resourceResult"/> </resultMap> <resultMap type="resource" id="resourceResult"> <id column="resid" property="id"/> <result column="resuri" property="uri"/> </resultMap>
<select id="findUserByUserName" parameterType="string" resultMap="userResult"> select u.id,u.username,r.id as rid,r.name as rname,r.des as rdes,p.id as pid,p.name as pname,res.id as resid,res.uri as resuri from tb_user u left join user_role ur on ur.user_id=u.id join tb_role r on r.id=ur.role_id join role_privilege rp on rp.role_id=r.id join tb_privilege p on p.id=rp.privilege_id join tb_resource res on res.privilege_id=p.id where u.username=#{username} </select>
5.UserMapper.java定义方法
@Component public interface UserMapper { User findUserByUserName(@Param(value="username")String username); }