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
。