模糊查询
一、在数据库中的模糊查询
select * from passenger_ft
查询所有名字中包含“三”的:
select * from passenger_ft where pname like '%三%'
就是通过Like关键字,和"_?%"等占位符来实现模糊查询的。
二、在ssm框架中实现模糊查询
1.list.jsp页面
<form name="f1" id="f1" action="getFlightByAddressAndTime" method="post" >
<div class="search-box clearfix">
<div class="content">
<div class="kv-item clearfix">
<label>出发城市:</label>
<div class="kv-item-content">
<input type="text" placeholder="出发城市" name="departureCity">
</div>
</div>
<div class="kv-item clearfix">
<label>到达城市:</label>
<div class="kv-item-content">
<input type="text" placeholder="到达城市" name="arrivalCity">
</div>
</div>
<div class="kv-item clearfix">
<label>出发日期:</label>
<div class="kv-item-content">
<input type="text" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})"
placeholder="出发日期" name="flightDate">
</div>
</div>
</div>
<button type="submit" class="sapar-btn sapar-btn-recom query-btn" >查询</button>
</div>
</form>
因为name名都是一个实体类的属性,则可用一个该实体类接收name传入的数据。
2.mapper
//操作flight表的规范
@Repository("FlightMapper")
public interface FlightMapper {
public List<Flight> selectCon(Flight flight);
}
3.mapper的映射文件
<select id="selectById" resultType="com.zqg.flight2.domain.Flight">
select * from flight where fid=#{fid}
</select>
<select id="selectCon" resultType="com.zqg.flight2.domain.Flight" >
<bind name="newDepartureCity" value="'%'+departureCity+'%'"/>
<bind name="newArrivalCity" value="'%'+arrivalCity+'%'"/>
select * from flight
<where>
<if test="departureCity!=null and departureCity!=''">
departure_city like #{newDepartureCity}
</if>
<if test="arrivalCity!=null and arrivalCity!=''">
and arrival_city like #{newArrivalCity}
</if>
<if test="flightDate!=null">
and flight_date = #{flightDate}
</if>
</where>
</select>
1.Date类型没有用like关键字的,也不能用空字符串。
2.where标签当一个字段没有时,可自动忽略and或or。
3.if标签可以将字段进行判断,限定。
4.bind标签可以将原字段进行拼接形成新字段。
5.传入的参数为实体类对象时,可自动将其属性作为传入的字段。
4.service调用
public List<Flight> selectCon(Flight flight){
List<Flight> list = flightMapper.selectCon(flight);
return list;
}
5.controller交互
@RequestMapping("/getFlightByAddressAndTime")
public String getFlightByAddressAndTime(@DateTimeFormat(pattern = "yyyy-MM-dd") Flight flight, Model model){
System.out.println(flight);
List<Flight> list = flightService.selectCon(flight);
System.out.println(list);
model.addAttribute("list",list);
return "flight/list";
}
6.domain实体类中
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date flightDate;
在实体类,controller和jsp文件中共同定义接收日期文件的格式。