解决MyBatis返回结果中有实体类没定义的属性

我的设计思想可能有问题,就是我如果能在sql里干的事情我一般不喜欢放到service里来做。目前我刚开始接触Mybatis,很难习惯查询什么都需要在实体类中加入getset方法,有点繁琐,自己写工具类水平又不够,这个问题让我很纠结。如果你的查询结果中有你用sql拼接而成的内容,而你的实体类中没有定义,mybatis的dao的xml可以这么写:
	<select id="SelectAllRoles" resultType="Hashmap">
	select  id, role, description, available ,
	(select  GROUP_CONCAT(m.name SEPARATOR ',')  from sys_powermenu pm,sys_resource m where pm.type=1 and  sys_role.id=pm.objid and pm.menuid=m.id) as menunames
      from sys_role   where 1=1 
	</select>
我自己拼接了一个属性menunames,类型为String,这样以来返回结果中有了实体类没有的属性,所以使用map来当结果集,在service里这样接收:
List<HashMap<String, Object>> list = dao.SelectAllRoles();

我前台使用的是EasyUI,我接收到数据没有什么问题。

下面是遇到一对多时可使用的自定义属性的例子:

<select id="menus" resultType="String">
	select  m.name as menunames  from sys_powermenu pm,sys_resource m where pm.type=1 and  pm.objid=#{xxx} and pm.menuid=m.id
	</select>
	<resultMap type="HashMap" id="xx">
	<id column="id" property="id"/>
	<result column="role" property="role"/>
	<result column="description" property="description"/>
	<result column="available" property="available"/>
	<collection property="menunames" ofType="String" select="menus" column="id" />
	</resultMap>
	<select id="SelectAllRoles" resultMap="xx">
	select  id, role, description, available 
      from sys_role   where 1=1 
	</select>

这个例子可能举得不合适,但格式就是这样,你可以在多表查询中取出任意表中的数据进行修改,然后传到前台进行展示,而不需要些那些该死的getset。

以后遇到问题的话,我会继续修改的。

一个Mybatis菜鸟在努力争扎。


猜你喜欢

转载自blog.csdn.net/baidu_36094751/article/details/79944216
今日推荐