Mybatis 查寻结果返回 Map、List〈Map〉
程序员文章站
2022-06-30 19:17:46
...
通常情况下,我们的查寻返回结果都会填充进相应的实体类中。
但有些特殊情况,我们返回的结果可能不是固定类型,这时可以使用 Map, List
com.jerry.mapper.TestMapper.java
package com.jerry.mapper;
import java.util.List;
import java.util.Map;
public interface TestMapper {
/**
* 查寻单个结果直接返回 Map<String, Object>
* @param id
* @return
*/
Map<String, Object> selectById(Long id);
/**
* 查寻结果列表返回 List<Map<String, Object>>
* @param paramsMap
* @return
*/
List<Map<String, Object>> selectList(Map<String, Object> paramsMap);
}
com.jerry.mapper.TestMapper.xml
<select id="selectById" resultType="map" parameterType="java.lang.Long">
select *
from test_table as tt
where tt.id = #{id}
</select>
<select id="selectList" resultType="map" parameterType="map">
select *
from test_table as tt
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<!-- 关键字查询 -->
<if test="keyWords != null and keyWords != ''">
AND (
IFNULL(tt.title, "") like "%"#{keyWords}"%"
or IFNULL(tt.keys, "") like "%"#{keyWords}"%"
)
</if>
<if test="searchType != null and searchType != ''">
AND tt.searchType = #{searchType}
</if>
</trim>
</select>
com.jerry.service.impl.TestService.java
package com.jerry.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(readOnly = true)
public class TestService implements ITestService {
@Resource
private TestMapper testMapper;
@Override
public Map<String, Object> allSearch(String keyWords, Integer searchType) {
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("keyWords", keyWords);
paramsMap.put("searchType", searchType);
List<Map<String, Object>> list = testMapper.listSearch(paramsMap);
return list.get(0);
}
}
上一篇: 用Mybatis返回Map,List
下一篇: 司机居然深藏不露