网站首页文章详情

MyBatis查询单条后显示null的问题解决方法

发布时间:2019-03-06 13:18编辑:胜男

<p> 在使用Mybatis做单条查询的时候,遇到查询出来本来有数据,可是打印出来的时候却是null,或者直接报【java.lang.NullPointerException】错误,效果如下:</p><pre class="prettyprint lang-js">==&gt;&nbsp;Preparing:&nbsp;select&nbsp;*&nbsp;from&nbsp;product_category&nbsp;where&nbsp;category_id=?&nbsp; ==&gt;&nbsp;Parameters:&nbsp;1(Integer) &lt;==&nbsp;Total:&nbsp;1&nbsp;null</pre><p>可以看出分明返回Total:1,查询出一条数据了,可以在打印的时候却是null,那是因为变量名没有打到对应的mysql字段列名,需要使用以下方案解决</p><p> 1、定义<span style="background-color:#EFEFEF;color:#000080;">resultMap</span></p><pre class="brush:xml;toolbar:false">&lt;resultMap&nbsp;id=&quot;resultMap&quot;&nbsp;type=&quot;ProductCategory&quot;&gt;&nbsp;&nbsp;&nbsp;&nbsp; &lt;id&nbsp;property=&quot;categoryId&quot;&nbsp;column=&quot;category_id&quot;&nbsp;/&gt;&nbsp;&nbsp;&nbsp;&nbsp; &lt;result&nbsp;property=&quot;categoryName&quot;&nbsp;column=&quot;category_name&quot;&nbsp;/&gt;&nbsp;&nbsp;&nbsp;&nbsp; &lt;result&nbsp;property=&quot;categoryType&quot;&nbsp;column=&quot;category_type&quot;&nbsp;/&gt;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/resultMap&gt;</pre><p></p><p> 2、在select标签里指定[resultMap],<span style="color:#E53333;">一定要注意select里的resultMap的值一定要与resultMap标签里的id的值保持一致</span></p><pre class="brush:xml;toolbar:false">&lt;select&nbsp;id=&quot;findOne&quot;&nbsp;resultType=&quot;ProductCategory&quot;&nbsp;resultMap=&quot;resultMap&quot;&gt;&nbsp;&nbsp;&nbsp;&nbsp; select&nbsp;*&nbsp;from&nbsp;product_category&nbsp;where&nbsp;category_id=#{categoryId}&nbsp;&nbsp;&nbsp;&nbsp; &lt;/select&gt;</pre><p><span style="font-family:Consolas, Monaco, " class="prettyprint lang-js">就可以了,效果如下</span></p><pre class="brush:xml;toolbar:false">==&gt;&nbsp;Preparing:&nbsp;select&nbsp;*&nbsp;from&nbsp;product_category&nbsp;where&nbsp;category_id=?&nbsp;&nbsp;&nbsp;&nbsp; ==&gt;&nbsp;Parameters:&nbsp;1(Integer)&nbsp;&nbsp;&nbsp;&nbsp; &lt;==Total:&nbsp;1&nbsp;ProductCategory{categoryId=1,&nbsp;categoryName=&#39;222&#39;,&nbsp;categoryType=92}</pre><p><br/></p>