动态搜索图书:可以按书名、作者、出版社以及价格范围进行搜索。(在IDEA中mybatis)

2022-12-12,,,,

中午找了好久、好多人写的都驴头不对马嘴。自己实现后、才发现是真的不麻烦、也不知道人家咋想的、写的死麻烦还没用。老是搜出sql语句写死的。我要的是动态滴。自己写出后、总结了一下

1、按照书名作者出版社搜索容易实现。这里就是对应数据库中的一个个字段、只需要在编写的sql中添加条件即可。
废话不多说、直接上代码:

前端(用来收集查询的条件):

 <div class="row ">
<form th:action="@{/book/bookList}" style="float: left"> <div class="col-md-2">
<input type="text" name="queryBookName" class="form-control" placeholder="书籍名">
</div>
<div class="col-md-2" >
<input type="text" name="queryBookAuthor" class="form-control" placeholder="作者名">
</div>
<div class="col-md-2" >
<input type="text" name="queryBookAddress" class="form-control" placeholder="出版社">
</div> <div class="col-md-4" >
<div class="col-row">
<div class="col-md-5">
<input type="text" name="minPrice" class="form-control" placeholder="最低价格">
</div>
<div class="col-md-1">
<span><strong>:</strong></span>
</div>
<div class="col-md-5">
<input type="text" name="maxPrice" class="form-control" placeholder="最高价格">
</div>
</div> </div>
<input type="submit" value="查询" class="btn btn-primary">
</form> </div>

实现的前端效果是这样的(我这里用的bootstrap) 其他的也可以、主要用来收集数据嘛。
用一个表单来收集数据、也可以单独的一个个数据的收集。使用表单收集数据还有的一个好处就是可以根据多个目标条件进行数据库的搜索。相当于一次性追加几个查询条件。

编写的sql语句、where 1=1 相当于sql语句不带任何的查询约束条件。等价于 select * from a
然后追加条件(我这里使用的mybatis框架、不影响sql语句的编写)

 <select id="queryBookList" parameterType="com.example.zheng.pojo.Books" resultType="com.example.zheng.pojo.Books">
select * from bookss
<where>
1=1
<if test="bookName != null and bookName != ''">
And bookName =#{bookName}
</if>
<if test="bookAuthor != null and bookAuthor != ''">
And bookAuthor =#{bookAuthor}
</if>
<if test="address != null and address !=''">
And address =#{address}
</if> </where>
</select>

重点在这里、怎样实现价格在一定范围内查询。由于价格是一个变化的、而且不和数据库中的字段对应。我首先想到的是 price >minPrice and price <maxPrice 。结果发现编写的sql语句报错、将编写的sql语句放入sql控制台查询是可以的、后来查阅资料发现。在mybatis中<是不能被识别的、需要使用转移字符 &lt;。我真的是靓仔无语。

1、前端页面定义参数、将数据收集。然后在后端将接受的数据封装到实体类中(在实体类中新增两个最大价格和最小价格的属性)。然后在进行查询就可以了。

   <if test="minPrice !=null and minPrice !=''">
And price > #{minPrice}
<if test="maxPrice !=null and maxPrice !=''">
And price &lt; #{maxPrice}
</if>
</if>

动态搜索图书:可以按书名、作者、出版社以及价格范围进行搜索。(在IDEA中mybatis)的相关教程结束。

《动态搜索图书:可以按书名、作者、出版社以及价格范围进行搜索。(在IDEA中mybatis).doc》

下载本文的Word格式文档,以方便收藏与打印。