mybatis多表關聯
阿新 • • 發佈:2018-05-11
接下來 jdb main方法 arch pri column pub main left
1.比如我有兩個一個是菜單表t_menu,一個是權限表t_jurisdiction.表結構如下:
2.我想要將這兩個表關聯,查詢特定的role_id下的菜單情況,這也是我們經常用在權限管理系統中的做法,將角色與菜單關聯起來。大概的sql語句如下
select t1.menu_id as menuId,t1.p_menu_id as pMenuId, t1.menu_name as menuName,ifnull(t2.jurisdiction_id,0) as jurisdictionId from t_menu t1 left join (select jurisdiction_id,menu_id fromt_jurisdiction where role_id=1)t2 on t1.menu_id=t2.menu_Id
該查詢會出現類似如下的結果。
其中jurisdictionId為0表示該用戶還沒選中這個菜單作為它的權限。
3.在mybatis中實現
首先,我們定義一個包含了上述字段的resultMap,將它的類型設為java.util.Map,如下所示:
<!-- 包含了菜單信息的權限列表 --> <resultMap id="ResultMapIncludeJurisdiction" type="java.util.Map"> <id column="menu_id" property="menuId" jdbcType="INTEGER" /> <result column="p_menu_id" property="pMenuId" jdbcType="INTEGER" /> <result column="menu_name" property="menuName" jdbcType="VARCHAR" /> <result column="jurisdiction_id" property="jurisdictionId" jdbcType="INTEGER" /> </resultMap>
然後,定義一個sql語句變量,如下
<sql id="Column_List_include_jurisdiction"> t1.menu_id, t1.p_menu_id,t1.menu_name,ifnull(t2.jurisdiction_id,0) </sql>
接下來就是查詢語句
<!-- 通過 roleId獲取其菜單列表,並標明是否有選中某項菜單--> <select id="selectJurisdictionByRoleId" parameterType="java.lang.Integer" resultMap="ResultMapIncludeJurisdiction"> select <include refid="Column_List_include_jurisdiction" /> from t_menu t1 left join (select jurisdiction_id,menu_id from t_jurisdiction where role_id=#{roleId,jdbcType=INTEGER}) t2 on t1.menu_id=t2.menu_id </select>
然後在Service層調用這個查詢語句就可以了
@Service public class JurisdictionService { @Resource(name="baseDao") private BaseDao<TJurisdiction,Integer>baseDao; public List<Map<String,Object>>getJurisdictionByRoleId(int roleId){ return baseDao.findMapListByPm("TJurisdictionMapper.selectJurisdictionByRoleId", roleId); } public static void main(String args[]){ ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); JurisdictionService jurisdictionService=(JurisdictionService) ctx.getBean("jurisdictionService"); System.out.println(jurisdictionService.getJurisdictionByRoleId(1)); } }
上述的main方法是用於測試的,測試結果符合我們的需要,關於baseDao的編寫,可參考博客其他文章。
<sql id="Column_List_include_jurisdiction">
t1.menu_id, t1.p_menu_id,t1.menu_name,ifnull(t2.jurisdiction_id,0)
</sql>
mybatis多表關聯