spring boot 与mybatis整合 采用注解方式进行拼接sql

spring boot 与mybatis 整合 首先先引入依赖 去maven 中央仓库查找mybatis依赖

 <!-- 引入mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

在application.yml写入连接数据库信息  type可以更改数据源配置 我这里采用的是 druid

采用注解开发 由与spring boot 底层自动配置已经配置好了一些基本配置 所以我们只需要创建一个接口来作为mapper并且加上注解@Mapper

import com.nice.straydogweb.bean.Color;
import com.nice.straydogweb.bean.Shape;
import com.nice.straydogweb.bean.Type;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
@Mapper
public interface SelectMapper {

    @Select("select * from color")
    List<Color> getColor();
    }

经过以上配置我们可以使用mybatis了 

采用注解形式进行sql拼接需要一个和特定注解

查询sql拼接 采用 @SelectProvider 如下

//查询已经和未领养的总条数 搜索
    @SelectProvider(type = SelectSql.class,method = "searchDogsCount")//通过类来反射sql语句
    Integer getYeSeTotaily(@Param("color") String color,@Param("type") String type,
                           @Param("shape") String shape,@Param("sex") String sex,@Param("flag") Integer flag);

SelectSql是一个进行拼接sql的类 后面是方法  如下

package com.nice.straydogweb.mapper;

import java.util.Map;

/**
 * 用来拼接sql语句
 */

public class SelectSql {


    public String searchDogsCount(Map<String,Object> map){
        String color= (String) map.get("color");
        String type= (String) map.get("type");
        String sex= (String) map.get("sex");
        String shape= (String) map.get("shape");
        Integer flag= (Integer) map.get("flag");
        String sql="select count(id) from dogs where 1=1";
        if(!color.equals(" ")){
            sql+=" and  color like '%"+color+"%'";
        }
        if(!type.equals(" ")){
            sql+=" and  type like '%"+type+"%'";
        }
        if(!sex.equals(" ")){
            sql+=" and  sex like '%"+sex+"%'";
        }
        if(!shape.equals(" ")){
            sql+=" and  shape like '%"+shape+"%'";
        }
        if(flag==2){
            //已经领养的
            sql+=" and state='2' ";
        }else{
            //未领养的
            sql+=" and state='1' ";
        }
        //sql+=" and state='1' ";
        System.err.println("Sql 语句 是"+sql);
        return sql;
    }
}
那个类的作用将生成拼接的sql返回回去 ,其中可以使用map进行参数传递。




扫描二维码关注公众号,回复: 2213800 查看本文章





猜你喜欢

转载自blog.csdn.net/youseenoonehere/article/details/81055693