1. mybatis中的動態(tài)SQL

        共 7539字,需瀏覽 16分鐘

         ·

        2021-10-01 13:18

        場景介紹

        如果只是簡單的CRUD, 可能只是需要一個parameterType就可以了, 當然這個接收參數(shù)可以是是自定義類型, 也可以是基本數(shù)據(jù)類型. 可是當傳入的參數(shù)個數(shù)不確定, 或者根據(jù)傳入的參數(shù)是否有值來決定生成什么樣的sql語句, 就需要用到mybatis的動態(tài)SQL功能了.

        項目中用到的xml

        mybatis映射表

        <?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="com.raylee.dao.UserMapper">

        <!-- sql語句抽取-->
        <sql id="selectUser">select * from users</sql>

        <!-- 根據(jù)條件判斷查詢操作-->
        <select id="findByCondition" resultType="user" parameterType="user">
        <include refid="selectUser"></include>
        <where>
        <if test="id != 0">
        id = #{id}
        </if>
        <if test="username != null">
        and username = #{username}
        </if>
        <if test="password != null">
        and password = #{password}
        </if>
        </where>
        </select>

        <!-- 根據(jù)集合查詢數(shù)據(jù)-->
        <select id="findByIds" parameterType="list" resultType="user">
        <include refid="selectUser"></include>
        <where>
        <foreach collection="list" open="id in (" close=")" item="id" separator=",">
        #{id}
        </foreach>
        </where>
        </select>
        </mapper>
        復制代碼

        mybatis配置表

        <?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">


        <configuration>
        <!-- 自定義別名-->
        <typeAliases>
        <typeAlias type="com.raylee.domain.User" alias="user"/>
        </typeAliases>

        <!-- 數(shù)據(jù)源環(huán)境-->
        <environments default="developement">
        <environment id="developement">
        <transactionManager type="JDBC"></transactionManager>
        <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/LCLDataBase"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        </dataSource>
        </environment>
        </environments>

        <!-- 加載核心配置文件-->
        <mappers>
        <mapper resource="UserMapper.xml"/>
        </mappers>
        </configuration>
        復制代碼

        項目中用到的java類

        接口

        public interface UserMapper {
        public List<User> findByCondition(User user);
        public List<User> findByIds(List<Integer> ids);
        }
        復制代碼

        User類

        public class User {
        private int id;
        private String username;
        private String password;

        public int getId() {
        return id;
        }

        public void setId(int id) {
        this.id = id;
        }

        public String getUsername() {
        return username;
        }

        public void setUsername(String username) {
        this.username = username;
        }

        public String getPassword() {
        return password;
        }

        public void setPassword(String password) {
        this.password = password;
        }

        @Override
        public String toString() {
        return "User{" +
        "id=" + id +
        ", username='" + username + '\'' +
        ", password='" + password + '\'' +
        '}';
        }
        }
        復制代碼

        項目中用到的數(shù)據(jù)庫表

        動態(tài)SQL - if標簽

        當我們使用普通的select標簽進行sql語句查詢時, 如果where后面的某個條件為空, 那么造成的后果可能就是查詢不到任何結果

        mybatis中xml的配置

         <select id="findByCondition" resultType="user" parameterType="user">
             select * from users where username = #{username} and password = #{password}
         </select>
        復制代碼

        調試代碼

         InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
         SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
         SqlSession sqlSession = build.openSession(true);
         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
         
         User user = new User();
         user.setId(1);
         user.setUsername("shaosiming");
         //       user.setPassword("123456");
         List<User> userList = mapper.findByCondition2(user);
         System.out.println(userList);
        復制代碼

        生成的sql語句和對應的參數(shù)

         select * from users where id = ? and username = ? and password = ?
         1(Integer), shaosiming(String), null
        復制代碼

        執(zhí)行的結果

        預期結果

        我們預期是當我們傳入的參數(shù)有值時, 都會將該條件拼接到where語句后面, 如果沒有值, 則不拼接

        使用標簽來完成這個功能

         <!--    根據(jù)條件判斷查詢操作-->
             <select id="findByCondition" resultType="user" parameterType="user">
                 <include refid="selectUser"></include>
                 <where>
                     <if test="id != 0">
                        and id = #{id}
                     </if>
                     <if test="username != null">
                        and username = #{username}
                     </if>
                     <if test="password != null">
                        and password = #{password}
                     </if>
                 </where>
             </select>
        復制代碼

        使用標簽后生成的sql語句和參數(shù)

        當使用標簽后, 如果有空的參數(shù), 則不會將該參數(shù)生成到sql語句中

         select * from users WHERE id = ? and username = ?
         1(Integer), shaosiming(String)
        復制代碼

        使用標簽后的結果

        [User{id=1, username='shaosiming', password='123456'}]

        動態(tài)SQL - foreach標簽

        當我們使用in語句要查詢多條數(shù)據(jù)時, 可能需要傳入一個集合當作參數(shù), 這里我們需要用到標簽

        mybatis中xml的配置

         <!--    根據(jù)集合查詢數(shù)據(jù)-->
             <select id="findByIds" parameterType="list" resultType="user">
                 <include refid="selectUser"></include>
                 <where>
                     <foreach collection="list" open="id in (" close=")" item="id" separator=",">
                        #{id}
                     </foreach>
                 </where>
             </select>
        復制代碼

        調試代碼

         InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
                 SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
                 SqlSession sqlSession = build.openSession(true);
                 UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                 
         ArrayList<Integer> ids = new ArrayList<>();
         ids.add(1);
         ids.add(2);
         ids.add(3);
         
         List<User> byIds = mapper.findByIds(ids);
         System.out.println(byIds);
        復制代碼

        生成的sql語句和參數(shù)

         select * from users WHERE id in ( ? , ? , ? ) 
         1(Integer), 2(Integer), 3(Integer)
        復制代碼

        執(zhí)行結果

        當前users表中只沒有id為3的數(shù)據(jù), 因此只查詢出來兩條

        [User{id=1, username='shaosiming', password='123456'}, User{id=2, username='dasiming', password='654321'}]

        SQL抽取 - sql標簽

         <sql id="selectUser">select * from users</sql>
        復制代碼

        SQL引入 - include標簽

         <include refid="selectUser"></include>


        作者:云淡風輕的博客
        鏈接:https://juejin.cn/post/7012502938878738440
        來源:掘金
        著作權歸作者所有。商業(yè)轉載請聯(lián)系作者獲得授權,非商業(yè)轉載請注明出處。



        瀏覽 64
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
          
          

            1. 日本cosme大赏美白 | 国产成人精品123区免费视频 | 日本囗交做爰视频 | www日韩无码 | 一級免費网站 |