MyBatis 동적 SQL 설정 프로 세 스 분석 실현

5164 단어 MyBatis동태SQL
동적 SQL
동적 SQL 이란 무엇 인가:
동적 SQL 은 서로 다른 조건 에 따라 서로 다른 SQL 문 구 를 생 성 하 는 것 이다.
  • if
  • choose(when,otherwise)
  • trim(where,set)
  • foreach
  • 1.환경 구축
    건축 표
    
    CREATE TABLE `bolg`(
      `id` VARCHAR(50) NOT NULL COMMENT '  id',
      `title` VARCHAR(100) not null comment '    ',
      `author` VARCHAR(30) not null comment '    ',
      `creat_time` datetime not null comment '    ',
      `views` int(30) not null comment '   '
    )ENGINE=InnoDB DEFAULT CHARSET=utf8
    기본 프로젝트 만 들 기
    가이드 백
    프로필 작성
    실체 클래스 작성
    
    @Data
    public class Blog {
      private int id;
      private String title;
      private String author;
      private Date creatTime;
      private int views;
    }
    실체 클래스 에 대응 하 는 Mapper 인터페이스 와 Mapper.xm 를 작성 합 니 다.
    2、IF
    
    <select id="queryBlogIF" parameterType="map" resultType="com.rui.pojo.Blog">
      select * from mybatis.bolg where 1=1
      <if test="title != null">
        and title = #{title}
      </if>
      <if test="author != null">
        and author = #{author}
      </if>
    </select>
    
    @Test
    public void queryBlogIF(){
      SqlSession sqlSession = MyBatisUtils.getSqlSession();
      BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
      HashMap map = new HashMap();
      map.put("author","  ");
      List<Blog> blogs = mapper.queryBlogIF(map);
      for (Blog blog : blogs) {
        System.out.println(blog);
      }
      sqlSession.close();
    }
    3、choose(when,otherwise)
    
    <select id="queryBlogChoose" parameterType="map" resultType="com.rui.pojo.Blog">
      select * from mybatis.bolg
      <where>
        <choose>
          <when test="title != null">
            title=#{title}
          </when>
          <when test="author!=null">
            and author = #{author}
          </when>
          <otherwise>
            and views = #{views}
          </otherwise>
        </choose>
      </where>
    </select>
    4、trim(where,set)
    
    select * from mybatis.bolg
    <where>
    <if test="title != null">
      title = #{title}
    </if>
    <if test="author != null">
      and author = #{author}
    </if>
    </where>
    
    <update id="updateBlog" parameterType="map">
      update mybatis.bolg
      <set>
        <if test="title != null">
          title = #{title},
        </if>
        <if test="author != null">
          author = #{author},
        </if>
      </set>
      where id = #{id}
    </update>
    동적 SQL 이란 본질 적 으로 SQL 문장 입 니 다.다만 우 리 는 SQL 차원 에서 논리 코드 를 실행 할 수 있 습 니 다.
    5、Foreach
    
    select * from user where 1=1 and 
     <foreach item="id" index="index" collection="ids"
       open="(" separator="or" close=")">
        #{id}
     </foreach>
    
    (id=1 or id=2 or id=3)
    
    <!--
    select * from mybatis.bolg where 1=1 and (id=1 or id=2 or id=3)
    
               map,  map       map
    -->
    <select id="queryBlogForeach" parameterType="map" resultType="com.rui.pojo.Blog">
      select * from mybatis.bolg
    
      <where>
      <foreach collection="ids" item="id" open="(" close=")" separator="or">
        id = #{id}
      </foreach>
      </where>
    </select>
    동적 SQL 은 SQL 문 구 를 연결 하 는 것 입 니 다.우 리 는 SQL 의 정확성 을 확보 하고 SQL 의 형식 에 따라 조합 을 배열 하면 됩 니 다.
    제안:
    먼저 MySQL 에 완전한 SQL 을 작성 한 다음 에 대응 하 는 것 을 수정 하여 우리 의 동적 SQL 로 만 듭 니 다.
    SQL 세 션
    때때로 우 리 는 일부 공공 부분 을 추출 처리 하여 재 활용 하기에 편리 할 수 있다.
    SQL 탭 을 사용 하여 공공 부분 을 추출 합 니 다.
    
    <sql id="if-title-author">
      <if test="title != null">
        title = #{title}
      </if>
      <if test="author != null">
        and author = #{author}
      </if>
    </sql>
    사용 할 곳 에 Include 탭 을 사용 하여 참조 하면 됩 니 다.
    
    <select id="queryBlogIF" parameterType="map" resultType="com.rui.pojo.Blog">
      select * from mybatis.bolg
      <where>
        <include refid="if-title-author"></include>
      </where>
    </select>
    주의사항:
    SQL 세 션 을 단일 테이블 로 정의 하 는 것 이 좋 습 니 다.
    where 나 set 탭 이 존재 하지 않 습 니 다.세 션 에 서 는 가능 한 한 if 만 있 으 면 됩 니 다.
    이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

    좋은 웹페이지 즐겨찾기