MyBatis基于注解模糊查询

import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Administrator
 * @date 2019/4/26 9:33
 */
public interface CustMapper {

    /**
     * 这里使用的是模糊查询
     * mybatis注解动态sql,有两种方式。
     * 这里使用的是<script>标签方式
     * 如果拼接普通的字符串要使用CONCAT
     * user是封装的另一个javaBean。这里单表的话可以删除
     * @param custName
     * @param custType
     * @return
     */
    @Select("<script>"+"SELECT c.*,u.`rolename` FROM s_cust c,s_user u WHERE c.`cust_link_user`=u.`uid`" and 1 = 1
            +"<if test='custName!=null'> and c.cust_name like CONCAT(CONCAT('%',#{custName}),'%')</if>"
            +"<if test='custType!=null'> and c.cust_type like CONCAT(CONCAT('%',#{custType}),'%')</if>"
            +"</script>"
            )
    @Results(@Result(property = "user.rolename",column = "rolename"))
    List<Cust> list(@Param("custName") String custName,@Param("custType")String custType);

    @Select("SELECT c.*,u.`rolename` FROM s_cust c,s_user u WHERE c.`cust_link_user`=u.`uid`")
    @Results(@Result(property = "user.rolename",column = "rolename"))
    List<Cust> listAll();

    @Delete("delete from s_cust where cid=#{cid}")
    int delete(Integer cid);

    @Insert("INSERT INTO `s_cust` (cust_name,cust_type,cust_phone,cust_address,cust_link_user) VALUES (#{s_cust.cust_name}, #{s_cust.cust_type},#{s_cust.cust_phone},#{s_cust.cust_address}, #{s_cust.cust_link_user});")
    int add(@Param("s_cust") Cust s_cust);
}

注意有三个细节:
①在使用mybatis开发的时候,有时候需要传入多个参数进行查询,当传入多个参数时,不处理便会出现上面的异常报错,这时需要用到一个注解@Param,否则会报如下错误:
在这里插入图片描述

②模糊查询的SQL语句中,concat是连接两个字符串的函数,这里连接了三个,要把SQL改成两个concat嵌套的

"<script>"+"SELECT * FROM product WHERE 1=1 "
            +"<if test='productName!=null'> and productName like CONCAT(CONCAT('%',#{productName}),'%')</if>"
            +"<if test='productDesc!=null'> and productDesc like CONCAT(CONCAT('%',#{productDesc}),'%')</if>"
            +"</script>"

否则会报如下错误:
在这里插入图片描述
③模糊查询的SQL这样写后,当参数为空时,会查询全部,所以这个SQL既能模糊查询,也能查询全部。在使用PageHelper的时候有用,例如,点击下一页的代码为:

<li><a href="${pageContext.request.contextPath}/product/findByNameAndDesc.do?productName=${search_productName}&productDesc=${search_productDesc}&page=${pageInfo.pageNum+1}&pageSize=${pageInfo.pageSize}">下一页</a></li>

这个下一页可能是查询全部的下一页,也有可能是模糊查询的下一页,所以当SQL这样写的时候,请求路径可以确定为:product/findByNameAndDesc.do

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值