場景:用戶表和角色表經過中間表關聯,要根據用戶id獲取用戶擁有的角色列表java
1、數據結構sql
一、用戶表數據庫
二、角色表數據結構
三、中間表app
方法一:在mapper類用註解,自定義sqlui
@Select("select r.name from sys_role r LEFT JOIN sys_uer_role ur on ur.role_id=r.id where uid=#{uid}") List<Role> getRoles(String userId);
方法二:xml自定義sqlcode
<resultMap id="BaseColumn" type="com.xiao.permission_system.entity.Role"> <id property="id" column="id" /> <result column="name" property="name" /> <collection property="users" ofType="com.xiao.permission_system.entity.UerRole"> <id property="id" column="role_id"/> </collection> </resultMap> <select id="getRoles" resultMap="BaseColumn"> select r.name from sys_role r LEFT JOIN sys_uer_role ur on ur.role_id=r.id where uid=#{uid} </select>
還可關聯上用戶表,以下xml
<resultMap id="BaseColumn" type="com.xiao.permission_system.entity.Role"> <id property="id" column="id" /> <result column="name" property="name" /> <collection property="uerRoles" ofType="com.xiao.permission_system.entity.UerRole"> <id property="id" column="role_id"/> <collection property="users" ofType="com.xiao.permission_system.entity.UserInfo"> <id property="id" column="id"/> <result column="username" property="username" /> <result column="password" property="password" /> </collection> </collection> </resultMap> <select id="getRoles" resultMap="BaseColumn"> select r.name,u.password,u.username from sys_role r LEFT JOIN sys_uer_role ur on ur.role_id=r.id LEFT JOIN sys_user_info u on u.id = ur.uid where u.id=#{uid} </select>
注:blog
一、property與java實體類的字段對應,column與數據庫字段對應。get
二、collection的id表示sys_uer_role與sys_role關聯的字段
三、select後的字段要在result裏寫明,好比select r.name對應了 <result column="name" property="name" />
四、這裏的實體能夠是與數據庫對應的實體,也能夠是自定義實體