Java 访问MyBatis中的私有超类字段
考虑以下POJO,它将用于保存将传递给查询的参数Java 访问MyBatis中的私有超类字段,java,exception,mybatis,Java,Exception,Mybatis,考虑以下POJO,它将用于保存将传递给查询的参数 public class RegionKey { private BigDecimal rgnId; private Country country; //setters and getters. } public class Country { private BigDecimal cntryId; //setters and g
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文件中的一个片段(查询1)
从客户中删除
其中CUST_ID={custRecord.custId,jdbcType=DECIMAL}
和RGN_ID=
将(#{custRecord.rgn.rgnId,jdbcType=CHAR}转换为CHAR(10))
上面的查询工作得非常好。如果测试工作正常,则使用以下命令修改上述查询(查询2)
从客户中删除
其中CUST_ID={custRecord.custId,jdbcType=DECIMAL}
和RGN_ID=cast(#{custRecord.RGN.rgnId,jdbcType=CHAR}as
字符(10))
按如下方式修改查询会导致运行时异常(查询3)
从客户中删除
其中CUST_ID={custRecord.custId,jdbcType=DECIMAL}
和CNTRY_ID=
强制转换(#{custRecord.rgn.country.cntryId,jdbcType=CHAR}为
字符(10))
对于查询3,我在运行时得到一个org.apache.ibatis.ognl.NoSuchPropertyException。我无法理解为什么会发生这种情况。如果我可以从查询2中的custRecord.rgn访问rgnId字段,那么从技术上讲,我应该能够从查询3中的custRecord.rgn.country访问cntryId字段 MyBatis期望(和大多数框架一样)“属性”遵循,因此属性foo
被映射到gettergetFoo()
和(可选)settersetFoo()
(私有字段的名称可以不同-它甚至可能不存在!-但通常它与属性相同)
所以,在你的例子中,你应该
public class RegionKey {
private Country country;
...
public Country getCountry() {
...
}
}
等等。Java IDE(如Eclipse)理解这一约定,并允许您为自己生成这些getter/setter,因此您不必键入它们。MyBatis期望(正如大多数框架所做的那样)“属性”遵循此约定,以便将属性foo
映射到gettergetFoo()
和(可选)settersetFoo()
(私有字段的名称可以不同-它甚至可能不存在!-但通常它与属性具有相同的名称)
所以,在你的例子中,你应该
public class RegionKey {
private Country country;
...
public Country getCountry() {
...
}
}
Java IDE(如Eclipse)理解此约定,并允许您为自己生成这些getter/setter,因此您不必键入它们。您确定getter/setter正常吗?
test=“custreck.rgn.country!=null”
还引发异常?作为MyBatis的新手,我不知道MyBatis会查找与属性同名的getter和setter。将getCntry方法重命名为getCountry成功了。非常感谢您提供的提示。您能否将此作为答案发布,以便我可以投票给您并接受答案?您确定getter/setter没有问题吗estest=“custRecord.rgn.country!=null”
还引发异常?作为MyBatis的新手,我不知道MyBatis会查找与属性同名的getter和setter。将getCntry方法重命名为getCountry成功了。非常感谢您提供的提示。您能否将此作为答案发布,以便我可以向上投票并接受答案?我已使用usi生成setter和getterng Eclipse。我碰巧重命名了字段,但忘了重命名setter和getter!我使用Eclipse生成了setter和getter。我碰巧重命名了字段,但忘了重命名setter和getter!
<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>
public class RegionKey {
private Country country;
...
public Country getCountry() {
...
}
}