国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

MyBatis多表查詢+動態(tài)sql

這篇具有很好參考價值的文章主要介紹了MyBatis多表查詢+動態(tài)sql。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。


MyBatis多表查詢

在全局配置文件中中設置MyBatis執(zhí)行日志

mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

1. 多表一對一查詢

假設有一個用戶表和文章表,實體類中一個關聯(lián)關系。

用戶實體類

@Getter
@Setter
@ToString
public class UserInfo {
    private int id;
    private String name;
    private String password;
}

文章實體類

@Data
public class BlogInfo {
    private int blogId;
    private String title;
    private String content;
    private Integer userId;
    private Timestamp postTime;
    private String time;
    private UserInfo userInfo;
}

如果想查詢的結果包含UserInfo的信息就需要使用,?對?映射要使? <association> 標簽,因為一篇文章只能對應一個作者。

Controller控制器代碼

@Controller
@ResponseBody
public class BlogController {
    @Resource
    private BlogService blogService;

    @RequestMapping("/getAllBlog")
    public List<BlogInfo> getAllBlog() {
        return blogService.getAllBlog();
    }
}

Service服務層代碼

@Service
public class BlogService {
    @Resource
    private BlogMapper blogMapper;
    public List<BlogInfo> getAllBlog() {
        return blogMapper.getAllBlog();
    }
}

BlogMap接口定義

@Mapper
public interface BlogMapper {

    List<BlogInfo> getAllBlog();
}

MyBatis接口實現(xiàn)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="com.example.demo.mapper.BlogMapper">
    <resultMap id="BlogBean" type="com.example.demo.model.BlogInfo">
        <!-- 映射主鍵 -->
        <id column="blogId" property="blogId"></id>
        <!-- 普通列映射(表字段->實體類) -->
        <result column="title" property="title"></result>
        <result column="content" property="content"></result>
        <result column="userId" property="userId"></result>
        <result column="postTime" property="postTime"></result>
        <!-- 關聯(lián)關系 -->
        <association property="userInfo"
                    resultMap="com.example.demo.mapper.UserMapper.UserBean"
                    columnPrefix="u_">

        </association>
    </resultMap>

    <select id="getAllBlog" resultMap="BlogBean">
        select u.userId u_userId,u.username u_username,b.blogId,b.title,b.postTime,b.userId from blog b left join user u on u.userId=b.userId
    </select>
</mapper>

使用<association>標簽,表示一對一的結果映射:

  • property屬性:指定文章類BlogInfo中對應的關聯(lián)屬性,也就是用戶實例userInfo
  • resultMap屬性:指定的是關聯(lián)關系的結果集映射,也就是UserInfo對象的屬性和表之間的映射關系
  • columnPrefix屬性:綁定一對一對象的時候,是通過columnPrefix+association.resultMap.column來映射結果集字段。association.resultMap.column是指 <association>標簽中 resultMap屬性,對應的結果集映射中,column字段 。

MyBatis多表查詢+動態(tài)sql

Postman測試打印的部分結果

[
    {
        "blogId": 2,
        "title": "Java基礎",
        "content": null,
        "userId": 1,
        "postTime": "2022-02-25T11:50:52.000+00:00",
        "time": null,
        "userInfo": {
            "id": 1,
            "name": "admin",
            "password": null
        }
    },
    {
        "blogId": 5,
        "title": "我的第一篇博客",
        "content": null,
        "userId": 1,
        "postTime": "2022-02-25T14:05:22.000+00:00",
        "time": null,
        "userInfo": {
            "id": 1,
            "name": "admin",
            "password": null
        }
    },

columnPrefix 如果省略,并且恰好兩個表中如果有相同的字段,那么就會導致查詢出錯

2. 多表一對多

一對多需要使用<collection>標簽,用法和<association>相同,比如說一個用戶可以發(fā)布多篇文章。

用戶實體類

@Getter
@Setter
@ToString
public class UserInfo {
    private int id;
    private String name;
    private String password;
    private List<BlogInfo> blogList;
}

映射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="com.example.demo.mapper.UserMapper">
    <resultMap id="UserMap" type="com.example.demo.model.UserInfo">
        <!-- 映射主鍵的(表中主鍵和程序實體類中的主鍵) -->
        <id column="userId" property="id"></id>
        <!-- 普通字段映射 -->
        <result column="username" property="name"></result>
        <result column="password" property="password"></result>

        <!-- 外部關聯(lián)管理 -->
        <collection property="blogList"
                    resultMap="com.example.demo.mapper.BlogMapper.BlogBean"
                    columnPrefix="b_">

        </collection>
    </resultMap>
    <select id="getAll" resultMap="UserMap">
        select u.userId,u.username,b.blogId b_blogId,b.title b_title,b.postTime b_postTime from user u left join blog b on u.userId=b.userId
    </select>


</mapper>
  • property屬性對應的是UserInfo類中的屬性blogList

Postman部分測試結果

MyBatis多表查詢+動態(tài)sql

動態(tài)SQL

動態(tài)SQL是MyBatis強大特征之一,在JDBC拼接SQL時候的痛處,不能忘記必要的空格添加,最后一個列名的逗號也要注意,利用動態(tài)SQL就能完成不同場景的SQL拼接。

MyBatis動態(tài)SQL

1.<if>標簽

在注冊某些賬號的填寫信息的時候,有必填項和非必填項,如果非必填項和少多寫個接口就好了,但如果非必填項非常多的話就不行了,這個時候就需要動態(tài)標簽<if>來判斷了。

這里假設性別和年齡是非必填項。

接口定義

int logonUser(String name, String password, String sex, Integer age);

數(shù)據(jù)表

+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| name     | varchar(50) | NO   |     | NULL    |                |
| password | varchar(25) | NO   |     | NULL    |                |
| sex      | varchar(10) | YES  |     | NULL    |                |
| age      | int(11)     | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

注意if<test=>是固定語法,里面的判斷的字段要和接口中定義的名字對應。

  • 如果滿足條件才會添加<if>里的文字
<?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.example.demo.mapper.UserMapper">

    <insert id="logonUser">
        insert into userInfo(id,name,password
        <if test="sex!=null">
            ,sex
        </if>
        <if test="age!=null">
            ,age
        </if>
        ) value(null,#{name},#{password}
        <if test="sex!=null">
            ,#{sex}
        </if>
        <if test="age!=null">
            ,#{age}
        </if>
        )
    </insert>

</mapper>

如果agesex都為null那么執(zhí)行的sql 就是

insert into userInfo(id,name,password ) value(null,?,? );

2.<trim>標簽

前面的新增用戶操作,agesex可能是選填項,如果有多個字段,一般考慮用<trim>標簽結合<if>標簽,對多個字段都采用動態(tài)生成的方式

<trim>標簽中有如下屬性

  • prefix:它表示整個語句塊,以prefix的值作為前綴(在語句塊最前面添加prefix字符)
  • suffix:它表示整個語句塊,以suffix的值作為后綴(在語句塊最后添加suffix字符)
  • prefixOverrides:表示整個語句塊要去除掉的前綴(刪除語句塊最前面滿足條件的字符)
  • suffixOverrides:表示整個語句塊要去除的后綴 (刪除語句塊最后面滿足條件的字符)

那么就可以將插入語句改成如下:

<?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.example.demo.mapper.UserMapper">

        <insert id="logonUser">
            insert into userInfo
            <trim prefix="(" suffix=")" suffixOverrides=",">
                id,name,password,
                <if test="sex!=null">
                    sex,
                </if>
                <if test="age!=null">
                    age
                </if>
            </trim>
            value
            <trim prefix="(" suffix=")" suffixOverrides=",">
            null,#{name},#{password},
            <if test="sex!=null">
                #{sex},
            </if>
            <if test="age!=null">
                #{age}
            </if>

            </trim>
        </insert>


</mapper>

假設調用接口的代碼是

userMapper.logonUser("張輝","123456","男",null);

最后執(zhí)行的SQL就是

insert into userInfo ( id,name,password, sex ) value ( null,?,?, ? )
  • 基于prefix 配置,開始部分加上 (
  • 基于suffix 配置,結束部分加上 )
  • 多個if都已,結尾,使用suffixOverrides就可以把末尾的,給去掉

3. <where>標簽

在使用查詢語句的時候,如果有多個條件就會用到邏輯運算,如果有些條件不滿足就會出現(xiàn)and前面沒有條件判,導致sql報錯

select * from userInfo where and sex!=null and age!=null;

使用<where>就可以很好的解決這個問題

  • 生成where,如果有查詢條件就會生成where,如果沒有查詢條件就會忽略where
  • where會判斷第一個查詢條件前面有沒有and,如果有則會刪除

查找接口定義

List<User> findAllUser(String sex, int age);
<?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.example.demo.mapper.UserMapper">
    <select id="findAllUser" resultType="com.example.demo.model.User">
        select * from userInfo
        <where>
            <if test="sex!=null">
                sex=#{sex}
            </if>
            <if test="age!=null">
                and age=#{age}
            </if>
        </where>
    </select>

</mapper>

以上<where>標簽也可以使 <trim prefix=“where” prefixOverrides="and> 替換

4.<set>標簽

根據(jù)傳入的用戶對象屬性來更新用戶數(shù)據(jù),可以使用<set>標簽來指定動態(tài)內容.

示例:

根據(jù)用戶Id來修改其它不為null的屬性

接口定義

int updateUserId(User user);

xml文件的接口實現(xiàn)

  • <set>也是會自動去除末尾的,
  • <set>標簽也可以使? <trim prefix="set" suffixOverrides=","> 替換
<?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.example.demo.mapper.UserMapper">
    <update id="updateUserId">
        update userInfo
        <set>
            <if test="name!=null">
                name=#{name},
            </if>
            <if test="password!=null">
                password=#{password},
            </if>
            <if test="sex!=null">
                sex=#{sex},
            </if>
            <if test="age!=null">
                age=#{age},
            </if>
        </set>
        where id=#{id}
    </update>

</mapper>

最后拼接的SQL

update userInfo SET name=?, password=?, sex=?, age=? where id=?

5. <foreach>標簽

對集合遍歷的時候可以使用該標簽,<foreach標簽有以下屬性:

  • conection:綁定方法中的集合,如 List、Set、Map或者數(shù)組對象
  • item:遍歷時的每一個對象
  • open:語句塊開頭的字符串
  • close:語句塊結束的字符串
  • separtor:每次遍歷之間間隔的字符串

假設要通過多個用戶id刪除多個用戶

接口定義和測試代碼

@Mapper
public interface UserMapper {
    // 方法定義
    int deleteListId(List<Integer> listId);
}


@SpringBootTest
class UserMapperTest {
    @Resource
    private UserMapper userMapper;

    @Test
    void deleteListId() {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);

        userMapper.deleteListId(list);
    }
}

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="com.example.demo.mapper.UserMapper">
    <delete id="deleteListId">
        delete from userInfo where id in
        <foreach collection="listId" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>

</mapper>

我的list集合里有3個用戶Id,最后拼裝的SQL文章來源地址http://www.zghlxwxcb.cn/news/detail-418393.html

delete from userInfo where id in ( ? , ? , ? )

到了這里,關于MyBatis多表查詢+動態(tài)sql的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!

本文來自互聯(lián)網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • Mybatis——多表查詢

    Mybatis——多表查詢

    目錄 一、簡介 二、業(yè)務環(huán)境的準備 2.1、準備工作: 2.2、SQL 三、一對一和一對多 Sql語句: POJO ?OrderMapper OrderMapper.xml ?Test測試類 運行結果 MyBatis 是一個優(yōu)秀的持久層框架,它提供了強大的支持來執(zhí)行數(shù)據(jù)庫操作,包括多表查詢。多表查詢是指從多個數(shù)據(jù)庫表中檢索數(shù)據(jù)的過

    2024年02月02日
    瀏覽(18)
  • MyBatis多表查詢和注解開發(fā)

    MyBatis多表查詢和注解開發(fā)

    一對一查詢的模型 用戶表和訂單表的關系為, 一個用戶有多個訂單,一個訂單只從屬于一個用戶 一對一查詢的需求:查詢一個訂單,與此同時查詢出該訂單所屬的用戶 一對一查詢的語句 對應的sql語句: 查詢的結果如下: 創(chuàng)建Order和User實體 創(chuàng)建OrderMapper接口 配置OrderMappe

    2024年02月04日
    瀏覽(29)
  • 【MyBatis】1、MyBatis 核心配置文件、多表查詢、實體映射文件 ......

    【MyBatis】1、MyBatis 核心配置文件、多表查詢、實體映射文件 ......

    SSM( S pring、 S pringMVC、 M yBatis) Apache Shiro SpringBoot 事務 :若將 N 個 數(shù)據(jù)庫操作 (CRUD)放到同一個事務中,則這 N 個數(shù)據(jù)庫操作最終要么全都生效,要么全都不生效 ?? 開啟事務【 START TRANSACTION 】 ?? 回滾事務:若事務中的某個數(shù)據(jù)庫操作失敗,其他所有數(shù)據(jù)庫操作都需要

    2024年02月08日
    瀏覽(58)
  • springboot和vue:七、mybatis/mybatisplus多表查詢+分頁查詢

    springboot和vue:七、mybatis/mybatisplus多表查詢+分頁查詢

    mybatisplus實際上只對單表查詢做了增強(速度會更快),從傳統(tǒng)的手寫sql語句,自己做映射,變?yōu)榉庋b好的QueryWrapper。 本篇文章的內容是有兩張表,分別是用戶表和訂單表,在不直接在數(shù)據(jù)庫做表連接的情況下,通過后臺代碼完成①查詢訂單的同時查到該訂單所屬的用戶,②

    2024年02月07日
    瀏覽(21)
  • mybatis-plus 多表關聯(lián)條件分頁查詢

    mybatis-plus 多表關聯(lián)條件分頁查詢

    此處以一對多,條件分頁查詢?yōu)槔?主表 明細表 0.請求dto 1.Controller 層: 注:我的項目中進行了service 讀寫分類配置,實際使用中,直接使用mybatis-plus中的 IUserService 對應的接口就行。 2.service 層 service impl實現(xiàn)層: 3.mapper 層 4.mapper.xml層 5.測試: 結果body: Q:todo page 分頁會把

    2024年02月12日
    瀏覽(30)
  • mybatis-plus分頁查詢(springboot中實現(xiàn)單表和多表查詢)

    mybatis-plus分頁查詢(springboot中實現(xiàn)單表和多表查詢)

    一、mybatis-plus單表查詢 使用mybatis-plus實現(xiàn)單表分頁查詢 非常方便,主要操作步驟如下: 配置分頁查詢攔截器 進行分頁查詢 1.首先,打開mybatis-plus官網的插件(插件主體) 或者點擊mybatis-plus插件 我是配置在springboot項目中,所以找到springboot的分頁配置 2.配置分頁查詢攔截器

    2024年02月08日
    瀏覽(16)
  • spring boot集成mybatis-plus——Mybatis Plus 多表聯(lián)查(包含分頁關聯(lián)查詢,圖文講解)...

    spring boot集成mybatis-plus——Mybatis Plus 多表聯(lián)查(包含分頁關聯(lián)查詢,圖文講解)...

    ?更新時間 2023-01-03 21:41:38 大家好,我是小哈。 本小節(jié)中,我們將學習如何通過 Mybatis Plus 實現(xiàn) 多表關聯(lián)查詢 ,以及 分頁關聯(lián)查詢 。 本文以 查詢用戶所下訂單 ,來演示 Mybatis Plus 的關聯(lián)查詢,數(shù)據(jù)庫表除了前面小節(jié)中已經定義好的用戶表外,再額外創(chuàng)建一張訂單表,然后

    2024年02月01日
    瀏覽(25)
  • 【MyBatis】攔截查詢結果同時動態(tài)替換

    項目中需要用到響應時替換某些字段的某些值。

    2024年02月04日
    瀏覽(31)
  • MyBatis動態(tài)SQL、模糊查詢與結果映射

    MyBatis動態(tài)SQL、模糊查詢與結果映射

    目錄 前言 一、MyBatis動態(tài)SQL 1.動態(tài)SQL是什么 2.動態(tài)SQL的作用 3.常用動態(tài)SQL元素 1. where + if 元素 2. set + if 元素 3. choose + when + otherwise 元素 4. 自定義 trim 元素 ?1. 自定義 trim 元素改寫上面的 where + if 語句 2. 自定義 trim 元素改寫上面的 set + if 語句 5. foreach 元素 6.SQL片段重用 二、

    2024年02月11日
    瀏覽(45)
  • 【已解決】Mybatis 實現(xiàn) Group By 動態(tài)分組查詢

    ??工作中遇到這樣一個需求場景:實現(xiàn)一個統(tǒng)計查詢,要求可以根據(jù)用戶在前端界面篩選的字段進行動態(tài)地分組統(tǒng)計。也就是說, 后端在實現(xiàn)分組查詢的時候,Group By 的字段是不確定的 ,可能是一個字段、多個字段或者不進行分組查詢,這都是由用戶在前端決定的。 ??這

    2024年02月11日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包