步骤5:在mybatis中使用query查询对象
第一步:创建BrandQuery对象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.mybatis.core.query; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class BrandQuery { 7 /** 8 * ================================like 查询 字段 9 */ 10 private String name; 11 private boolean nameLike; 12 public String getName() { 13 return name; 14 } 15 public void setName(String name) { 16 this.name = name; 17 } 18 public boolean isNameLike() { 19 return nameLike; 20 } 21 public void setNameLike(boolean nameLike) { 22 this.nameLike = nameLike; 23 } 24 25 /** 26 * =======================order by ================================================== 27 */ 28 29 public class OrderField 30 { 31 private String fieldName; 32 public OrderField(String fieldName, String order) { 33 super(); 34 this.fieldName = fieldName; 35 this.order = order; 36 } 37 private String order; 38 public String getFieldName() { 39 return fieldName; 40 } 41 public void setFieldName(String fieldName) { 42 this.fieldName = fieldName; 43 } 44 public String getOrder() { 45 return order; 46 } 47 public void setOrder(String order) { 48 this.order = order; 49 } 50 } 51 52 //创建orderField 集合 53 private List<OrderField> orderFields=new ArrayList<BrandQuery.OrderField>(); 54 55 //提供orderby + * 方法,传递要order by 的属性 例如: orderbyName(boolean isAsc) 56 57 public void orderByName(boolean isAsc) 58 { 59 orderFields.add(new OrderField("name",isAsc? "asc" : "desc")); 60 } 61 62 public void orderById(boolean isAsc) 63 { 64 orderFields.add(new OrderField("id",isAsc? "asc" : "desc")); 65 } 66 }
第二步:修改BrandDao.xml,增加fields过滤,like和order
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!-- 品牌选择器 --> <sql id="brandSelectorByFields"> SELECT <if test="fields != null"> ${fields} </if> <if test="fields == null"> id,name,description,img_url,web_site,sort,is_display </if> FROM bbs_brand </sql> <!-- 品牌条件 --> <sql id="brandWhere"> <where> <if test="name != null"> <if test="nameLike == false"> name = #{name} </if> <if test="nameLike == true"> and name like "%"#{name}"%" </if> </if> </where> </sql> <!-- order by --> <sql id="brandListOrder"> <if test="orderFields != null and orderFields.size > 0"> order by <foreach collection="orderFields" separator="," item="orderField"> ${orderField.fieldName} ${orderField.order} </foreach> </if> </sql> <select id="getBrandList2" parameterType="BrandQuery" resultMap="brand"> <include refid="brandSelectorByFields" /> <include refid="brandWhere" /> <include refid="brandListOrder" /> </select>
第三步:加入getBrandList2接口,加入测试代码
@Test public void TestGetBrandList2() { BrandQuery bQuery=new BrandQuery(); //设置过滤字段 bQuery.setFields("id,name"); //设置like 条件 bQuery.setNameLike(true); bQuery.setName("莲"); //设置order bQuery.orderById(true); List<Brand> brands= brandService.getBrandList2(bQuery); for (Brand brand1 : brands) { System.out.println(brand1.toString()); } }