Mybatis 裡對映檔案的動態 SQL 語句,實現if,where,foreache的SQL語句動態拼接查詢

Changan_py發表於2021-01-03


前言

提示:本文主要使用mybatis裡面對映檔案的方式,通過if,where和foreache來實現SQL語句動態拼接查詢


提示:以下是本篇文章正文內容,下面案例可供參考

一、配置步驟

  1. 搭建資料庫表user,設定有name、password、address三個欄位
    在這裡插入圖片描述
  2. 搭建目錄結構如下:
    在這裡插入圖片描述
  3. 首先匯入座標,pom.xml檔案,如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mybatis_day03_zj</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>

    </dependencies>
</project>

再配置資源設定resources下的日誌檔案log4j和SqlMapConfig.xml檔案
log4j.properties檔案:

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

SqlMapConfig.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的主配置檔案 -->
<configuration>
    <!-- 配置環境 -->
    <environments default="mysql">
        <!-- 配置mysql的環境-->
        <environment id="mysql">
            <!-- 配置事務的型別-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置資料來源(連線池) -->
            <dataSource type="POOLED">
                <!-- 配置連線資料庫的4個基本資訊 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_day01"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定對映配置檔案的位置,對映配置檔案指的是每個dao獨立的配置檔案 -->
    <mappers>
        <mapper resource="cn/it/dao/UserDao.xml"/>
    </mappers>
</configuration>

二、搭建好目錄結構後,進行實現

1.在domain實體目錄下封裝實體user,並實現get,set,toString方法

在這裡插入圖片描述

2.實現實體QueryVoc

package cn.it.domain;

import java.util.List;

public class QueryVo {
    private List<Integer> ids;

    public List<Integer> getIds() {
        return ids;
    }

    public void setIds(List<Integer> ids) {
        this.ids = ids;
    }
}

3.實現介面UserDao

程式碼如下(示例):

package cn.it.dao;

import cn.it.domain.QueryVo;
import cn.it.domain.Users;

import java.util.List;

public interface UserDao {

    List<Users> findAll();

    //動態查詢  <if>,<where>標籤模糊查詢
    List<Users> findByUser(Users user);

    //動態標籤<foreach>標籤
    List<Users> findByIds(QueryVo queryVo);
}

4.實現對映檔案UserDao.xml檔案

程式碼如下(示例):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.it.dao.UserDao">
    <!-- namespace:把要對映的介面路徑載入過來-->


    <!--表屬性和實體類對映別名-->
    <!--<resultMap id="userMap" type="cn.it.domain.Users">
        <id column="id" property="ID"/>
        <result column="name" property="user_Name"/>
        <result column="password" property="passWord"/>
        <result column="address" property="add_Ress"/>
    </resultMap>-->


    <!--查詢所有-->
    <select id="findAll" resultType="cn.it.domain.Users">
        SELECT  *  from users
    </select>

    <!--動態拼接查詢-->

    <!--定義aql片段-->
    <sql id="defaultSql">
           SELECT * from users
    </sql>
    <!--select * from users where 1=1-->
    <!--<if>,<where>標籤-->
    <select id="findByUser" resultType="cn.it.domain.Users" parameterType="cn.it.domain.Users">
        <include refid="defaultSql"></include>
        <where>
            <if test="name!=null and name != '' ">
                and name like #{name}
            </if>
            <if test="address != null">
                and address like #{address}
            </if>
        </where>
    </select>

    <!--foreach標籤 動態範圍查詢-->
    <select id="findByIds" resultType="cn.it.domain.Users" parameterType="cn.it.domain.QueryVo">
        <include refid="defaultSql"></include>
        <where>
            <if test="ids != null and ids.size() > 0">
                <foreach collection="ids" open="id in (" separator="," item="iditem" close=")">
                    #{iditem}
                </foreach>

            </if>
        </where>
    </select>

</mapper>

5.實現測試類test

在這裡插入圖片描述
程式碼如下(示例):

package cn.it.test;

import cn.it.dao.UserDao;
import cn.it.domain.QueryVo;
import cn.it.domain.Users;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class mybatis_test {

    //使用封裝的方式
    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession session;
    private UserDao userDao;

    //初始化方法
    @Before
    public  void init() throws IOException {
        //1.讀取配置檔案
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.建立SqlSessionFactory的構建者物件
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //3.使用構建者建立工廠物件 SqlSessionFactory
        factory = builder.build(in);
        //4.使用工廠生產SqlSession物件,設True自動提交事務openSession(True)
        session = factory.openSession();
        //5.使用SqlSession建立Dao介面的代理物件
        userDao = session.getMapper(UserDao.class);

    }

    //關閉資源
    @After
    public void closeResources() throws IOException{
        //移交表
        session.commit();
        //6.釋放資源
        session.close();
        in.close();

    }

    //查詢所有
    @Test
    public void findAll(){
        //5.使用代理物件執行方法
        List<Users> users = userDao.findAll();
        for(Users user : users){
            System.out.println(user);
        }
    }

    /*動態查詢,if,where標籤*/
    @Test
    public void testFindByUser() {
        Users u = new Users();
        u.setUsername("%強");
        u.setAddress("%深圳%");
        List<Users> users = userDao.findByUser(u);
        for(Users user1 : users) {
            System.out.println(user1);
        }
    }

    /*動態標籤之foreach標籤,實現範圍查詢*/
    @Test
    public void findByIDs(){
        QueryVo qVo = new QueryVo();
        ArrayList<Integer> ids = new ArrayList<Integer>();
        ids.add(3129);
        ids.add(3130);
        ids.add(3131);
        qVo.setIds(ids);
        List<Users> usersList = userDao.findByIds(qVo);
        for(Users users1: usersList){
            System.out.println(users1);
        }
    }

}

總結

提示:以上就是簡單的對mybatis對映檔案方式使用if、where和foreache對SQL語句動態拼接的實現內容,希望對您有用,感謝你的閱讀!!!

相關文章