關于mybatis一對一查詢一對多查詢遇到的問題
springboot整合mybatis項目
博客系統(tǒng)
文章,相冊,評論,標簽,等表
IDEA為最新版2021.3.3,mysql數(shù)據(jù)庫為最新版Navicat
(或許有些字段不支持特定的命名)
也是醉了,以前idea還是19版的,navicat也是老版本的時候mybatis關聯(lián)查詢mapper操作能正常運行,拿到相應字段,并封裝,但最近寫項目過程中遇到一個離譜的是,過了好久才發(fā)現(xiàn),
當關聯(lián)查詢時,無論一對一還是一對多
除了需要注意javaType和ofType之外,還應該注意各表主鍵不能同一名稱
實體類文章
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Article implements Serializable {
private Integer id;
private Integer authorId;
private String title;
private String content;
private Timestamp date;//private LocalDate date;
private Users user;
private List<Comment> commentList;
private List<ArticleTag> articleTagList;
}接下來是對文章進行操作,要求查詢?nèi)课恼?,并關聯(lián)查詢作者,文章標簽(一個文章多個標簽)
先看一下我下面代碼塊的寫法,注意一對一,一對多的各個實體查詢時的id,都是拿的數(shù)據(jù)庫的id字段,只有標簽被我改為了tag_id

<select id="queryAllArticles" resultMap="ArticleList">
select a.*,u.*,t.*
from article a
join users u on a.authorid = u.id
left outer join article_tag t on a.id = t.article_id
</select>
<resultMap id="ArticleList" type="article">
<id column="id" property="id"/>
<result column="authorid" property="authorId"/>
<result column="title" property="title"/>
<result column="content" property="content"/>
<result column="date" property="date"/>
<association property="user" javaType="users">
<id column="id" property="id"/>
<result column="pet_name" property="petName"/>
<result column="headportrait" property="headPortrait"/>
</association>
<collection property="articleTagList" ofType="articleTag">
<id column="tag_id" property="tagId"/>
<result column="article_id" property="articleId"/>
<result column="tag_content" property="tag"/>
</collection>
</resultMap>如下圖
所以當我測試的時候能正常根據(jù)id拿到每張表的同一主鍵名稱id嗎
并不能拿到
控制臺僅僅正確輸出了標簽list中的tag_id,沒錯,細心點,我也是最后才發(fā)現(xiàn),它nn的,上面輸出的user(文章作者)他的id封裝錯了,他的id是這篇文章的id,所以,sql我自此所有表的主鍵不都全命名為id了,防止此處再烙下病根,而且數(shù)據(jù)庫字段在命名時,我發(fā)現(xiàn)字段名字為describe和tag都查不到數(shù)據(jù),本來想簡簡單單命名的數(shù)據(jù)庫表,也得上心了拜拜了~~改bug去了????????????
///

看控制臺輸出/
我的用戶表里就沒有id為56的



到此這篇關于關于mybatis一對一查詢,一對多查詢遇到的錯誤的文章就介紹到這了,更多相關mybatis一對一查詢一對多查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JAVA代碼實現(xiàn)MongoDB動態(tài)條件之分頁查詢
這篇文章主要介紹了JAVA如何實現(xiàn)MongoDB動態(tài)條件之分頁查詢,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下2020-07-07
Java?Git?Commit?Message使用規(guī)范
這篇文章主要介紹了Java?Git?Commit?Message使用規(guī)范,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下,希望對你的學習有所幫助2022-08-08
SpringBoot整合ES-Elasticsearch的實例
這篇文章主要介紹了SpringBoot整合ES-Elasticsearch的實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

