2013-04-23 49 views
0

考慮以下將用於保存將傳遞給查詢的參數的POJO。訪問MyBatis中的私有超類字段

public class RegionKey { 

     private BigDecimal rgnId; 
     private Country country; 

     //setters and getters.  

     } 

public class Country { 

     private BigDecimal cntryId; 

     //setters and getters. 

     } 

public class Region extends RegionKey { 

     private String rgnNm; 
     private String desc; 

     //setters and getters 


    } 

    public class Customer { 
      private BigDecimal custId; 
      private Region rgn; 

     } 

考慮爲MyBatis的

public interface CustomerMapper { 

     int deleteByPrimaryKey(@Param("custRecord") Customer key); 
    } 

的CustomerMapper接口考慮從CustomerMapper.xml文件的一個片段(查詢1)

<delete id="deleteByPrimaryKey"> 
      delete from CUSTOMER 
      where CUST_ID = #{custRecord.custId,jdbcType=DECIMAL} 
      and RGN_ID = 
      cast(#{custRecord.rgn.rgnId,jdbcType=CHAR} as char(10)) 
    </delete> 

上述查詢工作完全正常。修改與以下,如果測試正常工作,以及(查詢2)

<delete id="deleteByPrimaryKey"> 
         delete from CUSTOMER 
         where CUST_ID = #{custRecord.custId,jdbcType=DECIMAL} 
         <if test="custRecord.rgn.rgnId != null"> 
        and RGN_ID = cast(#{custRecord.rgn.rgnId,jdbcType=CHAR} as 
        char(10)) 
         </if>     

       </delete> 

修改如下查詢上述查詢導致運行時異常(查詢3)

<delete id="deleteByPrimaryKey"> 
        delete from CUSTOMER 
        where CUST_ID = #{custRecord.custId,jdbcType=DECIMAL} 
        <if test="custRecord.rgn.country.cntryId != null"> 
       and CNTRY_ID = 
       cast(#{custRecord.rgn.country.cntryId,jdbcType=CHAR} as 
       char(10)) 
        </if> 



      </delete> 

我得到一個組織。 apache.ibatis.ognl.NoSuchPropertyException在運行時查詢編號3.我無法理解爲什麼發生這種情況。如果我可以在查詢2中訪問custRecord.rgn中的rgnId字段,那麼我應該可以在技術上訪問來自custRecord.rgn.country的查詢編號3中的cntryId字段。

+1

你確定getters/setters可以嗎? 'test =「custRecord.rgn.country!= null」'是否也會拋出異常? – leonbloy 2013-04-23 13:46:01

+0

MyBatis是MyBatis的新手,我不知道MyBatis會尋找與屬性名稱相同的getter和setter。將getCntry方法重命名爲getCountry取得了訣竅。非常感謝小費。你可以發佈這個答案,以便我可以upvote你並接受答案? – CKing 2013-04-23 14:00:36

回答

2

MyBatis預計(與大多數框架一樣)屬性「跟在Java Bean specs之後,所以屬性foo被映射到獲取者getFoo()和(可選)設置者setFoo()(私有字段的名稱可能不同 - 它甚至可能不存在! - 但它經常與屬性)。

所以,你比如說你應該有

public class RegionKey { 
     private Country country; 
     ... 
     public Country getCountry() { 
     ... 
     } 
} 

等。 Java IDE(例如Eclipse)理解這個約定,並允許你爲你生成這些getter/setters,所以你不必輸入它們。

+0

我已經使用Eclipse生成了setter和getters。我碰巧重命名了這個字段,但忘了重命名setter和getters! – CKing 2013-04-24 05:33:25