基于mybatis查詢結果映射不到對象的處理
mybatis查詢結果映射不到對象
項目場景
使用mybatis+springboot 進行數(shù)據(jù)庫的數(shù)據(jù)查詢操作,一直拿不到返回結果。
問題描述
后端dao層(service層調mapper,方法的返回結果一直null)代碼一直空指針,
APP 中接收數(shù)據(jù)代碼:
//分類名稱 Integer blogCategoryId = blog.getBlogCategoryId();//這里有數(shù)據(jù) 22 BlogCategory category = blogCategoryMapper.getCategoryById(blogCategoryId);//這里返回結果就一直null blog.setBlogCategoryName(category.getCategoryName());//導致這里一調用方法就報空指針了。
原因分析
仔細檢查了代碼(debug),controller層+ service層沒問題,那問題坑定再dao層。檢查xml文件,但發(fā)現(xiàn)xml文件中查詢方法的sql代碼寫的沒問題:
<select id="getCategoryById" parameterType="java.lang.Integer" resultType="com.hhh.blog.entity.BlogCategory"> SELECT category_id, category_name, category_icon, category_rank, create_time, is_deleted FROM tb_blog_category WHERE category_id = #{blogCategoryId} </select>
這里理論上沒啥問題,但特么的就是數(shù)據(jù)庫的數(shù)據(jù)映射不到對象中(實體類都是按照數(shù)據(jù)庫數(shù)據(jù)對應的,只多不少)。
解決方案
resultType=“com.hhh.blog.entity.BlogCategory”
返回結果改成使用映射:
<select id="getBlogCategoryPage" resultMap="getBlogCategoryPageMap"> <resultMap id="getBlogCategoryPageMap" type="com.hhh.blog.entity.BlogCategory"> <id column="category_id" jdbcType="INTEGER" property="categoryId" /> <result column="category_name" jdbcType="VARCHAR" property="categoryName" /> <result column="category_icon" jdbcType="VARCHAR" property="categoryIcon" /> <result column="category_rank" jdbcType="INTEGER" property="categoryRank" /> <result column="is_deleted" jdbcType="TINYINT" property="isDeleted" /> <result column="create_time" jdbcType="DATE" property="createTime" /> </resultMap>
開啟駝峰式命名匹配也可能解決上述問題。沒試過。建議自己搞起來
mybatis結果映射遇到的問題
錯誤如下
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.executor.ExecutorException: No constructor found in POJO.User matching [java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.String]
### The error may exist in Mapper/UserMapper
### The error may involve test.selectUserById
### The error occurred while handling results
### SQL: SELECT * FROM USER WHERE id=?
### Cause: org.apache.ibatis.executor.ExecutorException: No constructor found in POJO.User matching [java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.String]
解決方案
最后,將User構造器中int改為Integer即可、
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解Java并發(fā)工具類之CountDownLatch和CyclicBarrier
在JDK的并發(fā)包中,有幾個非常有用的并發(fā)工具類,它們分別是:CountDownLatch、CyclicBarrier、Semaphore和Exchanger,本文主要來講講其中CountDownLatch和CyclicBarrier的使用,感興趣的可以了解一下2023-06-06Opencv創(chuàng)建車牌圖片識別系統(tǒng)方法詳解
本文主要介紹了一個基于spring?boot+maven+opencv實現(xiàn)的圖像識別及訓練項目,可以實現(xiàn)車牌識別功能,感興趣的可以跟隨小編一起試一試2022-01-01JAVA使用POI獲取Excel的列數(shù)與行數(shù)
Apache POI 是用Java編寫的免費開源的跨平臺的 Java API,Apache POI提供API給Java程式對Microsoft Office格式檔案讀和寫的功能。 下面這篇文章給大家介紹了JAVA使用POI獲取Excel列數(shù)和行數(shù)的方法,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-12-12