访问MyBatis中的私有超类字段

时间:2013-04-23 13:35:50

标签: java exception mybatis

考虑以下用于保存将传递给查询的参数的POJO。

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的CustomerMapper接口

public interface CustomerMapper {

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

考虑CustomerMapper.xml文件(QUERY 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>

以上查询完美无缺。使用以下if-test修改上述查询也可以正常工作(查询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>

我在运行时为查询号3得到一个org.apache.ibatis.ognl.NoSuchPropertyException。我无法理解为什么会发生这种情况。如果我可以从查询2中的custRecord.rgn访问rgnId字段,我在技术上应该能够从查询号3中的custRecord.rgn.country访问cntryId字段。

1 个答案:

答案 0 :(得分:4)

MyBatis希望(正如大多数框架所做的那样)“属性”遵循Java Bean specs,以便将属性foo映射到getter getFoo()和(可选)setter {{ 1}}(私有字段的名称可以不同 - 甚至不存在! - 但通常它与属性相同)。

所以,在你的例子中你应该有

setFoo()

等等。 Java IDE(例如Eclipse)理解这个约定,并允许您为您生成这些getter / setter,因此您不必键入它们。