mybatis多表关联

时间:2022-04-24 05:53:28

1.比如我有两个一个是菜单表t_menu,一个是权限表t_jurisdiction.表结构如下:

mybatis多表关联

mybatis多表关联

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 from t_jurisdiction where role_id=1)t2 on t1.menu_id=t2.menu_Id

该查询会出现类似如下的结果。

mybatis多表关联

其中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) as jurisdiction_id
</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>