The multi-criteria query server case

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/ym15229994318ym/article/details/102633902

Tim pieces of multi-combination search

Give the project take a stand (built package)

  • com.baidu.custmer.domain
  • com.baidu.custmer.dao
  • com.baidu.custmer.service
  • com.baidu.custmer.web.servlet
    four packages are responsible for different layers: domain object persistence layer, service layer, web layer

Multi-criteria query process

  1. Page send queries, send a query message to the server (that is, a form of information)
  2. Server receives the request, Servlet to process the request
    • Package information request form the domain to domain object
    • The method calls business layer service, transmitting condition, this condition is the second step of the domain object, and returns a set of List
    • And save the result set in the request domain
    • Forwarded to display query results page
  3. Business layer (business layer where really did not do anything, just call a method in Dao, if the project is large enough it will reflect the business layer)
    ** 4. Dao in the query **
    Here Insert Picture Description
    ** here only demonstrates more than For inquiries about the condition code **

com.baidu.custmer.domain

It is a customer type, domain domain objects

package cn.itcast.cstm.domain;

/**
 * 领域对象
 * 与表单和数据库表对应
 */
public class Customer {
    private String cid;//主键id
    private String cname;//姓名
    private String gender;//性别
    private String birthday;//生日
    private String cellphone;//电话
    private String email;//邮箱
    private String description;//描述

    public Customer() {
    }

    public Customer(String cid, String cname, String gender, String birthday, String cellphone, String email, String description) {
        this.cid = cid;
        this.cname = cname;
        this.gender = gender;
        this.birthday = birthday;
        this.cellphone = cellphone;
        this.email = email;
        this.description = description;
    }

    public String getCid() {
        return cid;
    }

    public void setCid(String cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getCellphone() {
        return cellphone;
    }

    public void setCellphone(String cellphone) {
        this.cellphone = cellphone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "cid='" + cid + '\'' +
                ", cname='" + cname + '\'' +
                ", gender='" + gender + '\'' +
                ", birthday='" + birthday + '\'' +
                ", cellphone='" + cellphone + '\'' +
                ", email='" + email + '\'' +
                ", description='" + description + '\'' +
                '}';
    }

}

com.baidu.custmer.web.servlet

We hope to have more than one request processing method in a Servlet in! We ask the client sends when requesting to be given a multi-parameter, used to illustrate the method to invoke request processing method signature must be the same as the service that return values ​​and parameters, and exceptions are identical statement! The client must pass the page parameter named method! The method parameter value is passed here like query.

<form action="<c:url value='/CustomerServlet'/>" method="post">
	<input type="hidden" name="method" value="query">
<table border="0" align="center" width="40%" style="margin-left: 100px;">
	<tr>
		<td width="100px">客户名称</td>
		<td width="40%">
			<input type="text" name="cname"/>
		</td>
	</tr>
	<tr>
		<td>客户性别</td>
		<td>
			<select name="gender">
				<option value="">==请选择性别==</option>
				<option value=""></option>
				<option value=""></option>
			</select>
		</td>
	</tr>
	<tr>
		<td>手机</td>
		<td>
			<input type="text" name="cellphone"/>
		</td>
		<td>
			<label id="cellphoneError" class="error">&nbsp;</label>
		</td>		
	</tr>
	<tr>
		<td>邮箱</td>
		<td>
			<input type="text" name="email"/>
		</td>
		<td>
			<label id="emailError" class="error">&nbsp;</label>
		</td>	
	</tr>
	<tr>
		<td>&nbsp;</td>
		<td>
			<input type="submit" value="搜索"/>
			<input type="reset" value="重置"/>
		</td>
		<td>&nbsp;</td>
	</tr>
</table>
</form>
	

CustomerServlet here is inherited from BaseServlet, BaseServlet inherited from HttpServlet,
which is BaseServlet is actually a project servlet avoid explosion.

@WebServlet("/CustomerServlet")
public class CustomerServlet extends BaseServlet {
    private CustomerService customerService = new CustomerService();
    
    private CustomerDao customerDao = new CustomerDao();
    
    /**
     * 多条件组合查询
     *
     * @param request
     * @param response
     * @return
     */
    public String query(HttpServletRequest request, HttpServletResponse response) {
        /*
        1.封装表单数据到Customer对象中,他只有四个属性(cname,gender,cellphone,email)其实就是条件
        2.使用Customer调用service方法,得到List<Customer>
        3.保存到request域中
        4.转发到list.jsp
         */
        Customer criteria=CommonUtils.toBean(request.getParameterMap(),Customer.class);
        List<Customer> cstmList=customerService.query(criteria);
        request.setAttribute("cstmList",cstmList);
        return "f:/list.jsp";
    }
}

com.baidu.custmer.service

Here is a simple service layer method calls Dao in it.

/**
 * 业务层
 */
public class CustomerService {
    private CustomerDao customerDao = new CustomerDao();
    
    /**
     * 多条件组合查询
     * @param criteria
     * @return
     */
    public List<Customer> query(Customer criteria) {
        return customerDao.query(criteria);
    }
}

com.baidu.custmer.dao

This place really is learned. Ha ha ha!

We can see from com.baidu.custmer.web.servlet the query form form, he actually have multiple conditions, we do not know how users search, for example: users choose a few conditions here will involve arrangement combination problem? Is really the first time I thought of permutations and combinations, then, how many layers if-else condition to determine how many sql statement that to write it? In case the customer requires an increase in the query form, it was not in vain. ……How to do it

dao in multi-criteria query process (focus)

1. The template is given sql (sql focus is how to write, how to determine the conditions)
* first gave the first part of a sql statement
* judgment conditions, the completion of additional sql where clause
* do not tangle the user whether the conditions to which the use of which condition not in use it is to determine whether the write and or where, we use 1 = 1 such a nonsense, instead of the condition, and can write all behind, (although this basis but still felt very first time I saw Cock !!!) *
* ArrayList to create a load parameter value
2. The given parameters
3. BeanListHandler processor invokes query result set method

/**
 * 持久层
 */
public class CustomerDao {
    private QueryRunner qr = new TxQueryRunner();
    
    /**
     * 多条件组合查询
     *
     * @param criteria
     * @return
     */
    public List<Customer> query(Customer criteria) {
        try {
            /*
            1.给出sql模板
            2.给出参数
            3.调用query方法,使用BeanListHandler结果集处理器
             */
            //1.给sql模板
            //先给出一个sql语句前半部分
            StringBuilder sql = new StringBuilder("select * from t_customer where 1=1");
            //判断条件,完成sql中追加where字句
            //创建一个ArrayList用来装载参数值
            List<Object> params = new ArrayList<>();

            String cname = criteria.getCname();
            if (cname != null && !cname.trim().isEmpty()) {
                sql.append(" and cname like ?");
                params.add("%"+cname+"%");
            }

            String gender = criteria.getGender();
            if (gender != null && !gender.trim().isEmpty()) {
                sql.append(" and gender=?");
                params.add(gender);
            }

            String cellphone = criteria.getCellphone();
            if (cellphone != null && !cellphone.trim().isEmpty()) {
                sql.append(" and cellphone like ?");
                params.add("%"+cellphone+"%");
            }

            String email = criteria.getEmail();
            if (email != null && !email.trim().isEmpty()) {
                sql.append(" and email like ?");
                params.add("%"+email+"%");
            }

            /*
            执行query
             */
            return qr.query(sql.toString(), new BeanListHandler<Customer>(Customer.class), params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

Guess you like

Origin blog.csdn.net/ym15229994318ym/article/details/102633902