需求
-
最近遇到一个事情,前端某个请求只需要后端实体类中的某几个属性,但是数据库中却定义了其他属性,我们如何把其他属性的值排除在外,只获取我们需要的属性值呢?
-
原本数据库字段,有很多,但是我们只需要某些字段
<resultMap type="SheepGenealogy" id="SheepGenealogyResult">
<result property="id" column="id" />
<result property="eartagid" column="eartagid" />
<result property="sex" column="sex" />
<result property="farmloc" column="farmloc" />
<result property="bornloc" column="bornloc" />
<result property="region" column="region" />
<result property="buildingnum" column="buildingnum" />
<result property="columnnum" column="columnnum" />
<result property="borntime" column="borntime" />
<result property="bornweight" column="bornweight" />
<result property="breed" column="breed" />
<result property="coatcolor" column="coatcolor" />
<result property="motherid" column="motherid" />
<result property="fatherid" column="fatherid" />
<result property="grandfatherid" column="grandfatherid" />
<result property="grandmotherid" column="grandmotherid" />
<result property="grandpaid" column="grandpaid" />
<result property="grandmaid" column="grandmaid" />
<result property="video" column="video" />
<result property="bak1" column="bak1" />
<result property="bak2" column="bak2" />
<result property="bak3" column="bak3" />
<result property="createBy" column="create_by" />
<result property="createDate" column="create_date" />
<result property="updateBy" column="update_by" />
<result property="updateDate" column="update_date" />
<result property="remarks" column="remarks" />
<result property="delFlag" column="del_flag" />
</resultMap>
解决
- 自己定义一个resultMap
- type=“java.util.HashMap”
<resultMap type="java.util.HashMap" id="SheepSpeciesResult">
<result property="breed" column="breed" />
<result property="bak1" column="bak1" />
</resultMap>
- sql语句
<select id="selectSheepGenealogysheepSpecies" resultMap="SheepSpeciesResult">
SELECT breed,COUNT(breed) bak1 from sheep_genealogy GROUP BY breed
</select>
-
同时把你的service和mapper文件里面的对应的方法返回值类型改成List<Map<String, Object>>
-
mapper
public List<Map<String, Object>> selectSheepGenealogysheepSpecies();
- service
public List<Map<String, Object>> selectSheepGenealogysheepSpecies() {
System.out.println(sheepGenealogyMapper.selectSheepGenealogysheepSpecies());
return sheepGenealogyMapper.selectSheepGenealogysheepSpecies();
}
- 前端请求结果