考虑以下 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 接口(interface)
public interface CustomerMapper {
int deleteByPrimaryKey(@Param("custRecord") Customer key);
}
考虑 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>
上面的查询工作得很好。使用以下 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 字段。
最佳答案
MyBatis 期望(像大多数框架一样)“属性”遵循 Java Bean specs ,以便属性 foo
映射到 getter getFoo()
和(可选)setter setFoo()
(私有(private)属性的名称)字段可以不同 - 它甚至可以不存在! - 但很多时候它与属性相同)。
所以,在你的例子中你应该有
public class RegionKey {
private Country country;
...
public Country getCountry() {
...
}
}
等等。 Java IDE(例如 Eclipse)了解此约定,并允许您生成这些 getter/setter,因此您无需键入它们。
关于java - 访问 MyBatis 中的私有(private)父类(super class)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16170773/