Mybatis如何解決範圍查詢
阿新 • • 發佈:2019-01-31
今天進行了一個嘗試,嘗試背景是:
先設定了一個Goods類,裡面存在屬性price,
但是,我現在要進行範圍查詢,也就是price > ? and price < ?,但是,如果在向statement傳入Goods這個實體類時,只能給一個price賦值,而標籤卻要寫兩個if進行判斷。下面進行程式碼示例:
Goods類的屬性資訊:類中包含get、set方法,此處沒有複製。
public class Goods { private int id; private String name; private String description; private double price;
mapper.xml檔案
<mapper namespace="Goods">
<select id="selByCondition4if" resultType="com.test.pojo.Goods">
select * from TestMybatis
<where>
<if test="id > 0">
and id = #{id}
</if>
<if test="name != null and name.trim().length() > 0">
and name like '%'||#{name}||'%'
</if>
<if test="description != null and description.trim().length() > 0">
and description like '%'||#{description}||'%'
</if>
<if test="price > 0">
and price > #{price}
</if>
<if test="price2 > 0">
and price < #{price2}
</if>
</where>
</select>
</mapper>
為了解決這個問題,我新增加了一個類叫做GoodsModel.java,並讓該類繼承Goods類,裡面只有一個屬性是price2,並生成get、set方法。
public class GoodsModel extends Goods{ private double price2; public double getPrice2() { return price2; } public void setPrice2(double price2) { this.price2 = price2; } }
這樣就可以對mapper.xml檔案傳入GoodsModel的物件,這樣就不僅包含了Goods的所有屬性,還包含了範圍查詢的另一個price的值,下面是測試程式碼:
public class TestApp {
public static void main(String[] args) throws Exception {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
GoodsModel goodsModel = new GoodsModel();
goodsModel.setId(1);
goodsModel.setName("c");
goodsModel.setDescription("c");
goodsModel.setPrice(2d);
goodsModel.setPrice2(5d);
List<Goods> list = sqlSession.selectList("Goods.selByCondition4if", goodsModel);
System.out.println(list);
sqlSession.close();
}
}
這樣就可以得到結果了,控制檯輸出為
DEBUG [main] - ==> Preparing: select * from TestMybatis WHERE id = ? and name like '%'||?||'%' and description like '%'||?||'%' and price > ? and price < ?
DEBUG [main] - ==> Parameters: 1(Integer), c(String), c(String), 2.0(Double), 5.0(Double)
DEBUG [main] - <== Total: 1
[Goods [id=1, name=cathy, description=cathyy, price=3.0]]
下面額外進行了一個測試,我在思考,如果我繼續向statement出入Goods物件,也就意味著不存在price2,那麼 <if test="price2 > 0">
and price < #{price2}
</if>
是否還會生效,於是測試程式碼就變更為:
public class TestApp {
public static void main(String[] args) throws Exception {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
//GoodsModel goodsModel = new GoodsModel();
Goods goods = new Goods();
goods.setId(1);
goods.setName("c");
goods.setDescription("c");
goods.setPrice(2d);
//goodsModel.setPrice2(5d);
List<Goods> list = sqlSession.selectList("Goods.selByCondition4if", goods);
System.out.println(list);
sqlSession.close();
}
}
最後控制檯輸出為
There is no getter for property named 'price2' in 'class com.test.pojo.Goods'
看來if語句裡的每一個test都是要去傳入的實體類中尋找get方法,而不是依靠傳入的goods是否有寫set這個屬性。