查询列表
相对查询最多1个数据,查询列表的区别在于:必须使用List
类型作为抽象方法的返回值类型,另外,在配置<select>
时,无论使用resultType
还是resultMap
,在指定封装返回结果的类型时,仍指定List
中的元素类型即可。
【需求】查询品牌列表,暂不考虑分页,结果按照sort
降序排列、id
升序(降序)。
需要执行的SQL语句大致是:
select
id, name, pinyin, logo, description,
keywords, sort, sales, product_count, comment_count,
positive_comment_count, enable
from pms_brand order by sort desc, id
通常,查询列表时,与查询单个数据使用的VO类应该是不同的。
则在项目的根包下创建pojo.vo.BrandListItemVO
类,在类中声明与以上字体列表匹配的属性:
package cn.tedu.csmall.product.pojo.vo;
import lombok.Data;
import java.io.Serializable;
@Data
public class BrandListItemVO implements Serializable {
private Long id;
private String name;
private String pinyin;
private String logo;
private String description;
private String keywords;
private Integer sort;
private Integer sales;
private Integer productCount;
private Integer commentCount;
private Integer positiveCommentCount;
private Integer enable;
}
在BrandMapper.java
接口中添加抽象方法:
/**
* 查询品牌列表
*
* @return 品牌列表,如果没有匹配的品牌,将返回长度为0的列表
*/
List<BrandListItemVO> list();
在BrandMapper.xml
中配置SQL:
<select id="list" resultMap="ListResultMap">
SELECT
<include refid="ListQueryFields"/>
FROM
pms_brand
ORDER BY
sort DESC, id
</select>
<sql id="ListQueryFields">
<if test="true">
id, name, pinyin, logo, description,
keywords, sort, sales, product_count, comment_count,
positive_comment_count, enable
</if>
</sql>
<resultMap id="ListResultMap"
type="cn.tedu.csmall.product.pojo.vo.BrandListItemVO">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="product_count" property="productCount"/>
<result column="comment_count" property="commentCount"/>
<result column="positive_comment_count" property="positiveCommentCount"/>
</resultMap>
完成后,在BrandMapperTests
中编写并执行测试:
@Test
void testList() {
List<BrandListItemVO> list = mapper.list();
System.out.println("查询品牌列表,查询结果中的数据的数量:" + list.size());
for (BrandListItemVO brand : list) {
System.out.println(brand);
}
}