我定义了一个JavaBean:public class City {
private int id;
private String name;
private String des; public City(int _id) {
id = _id;
} public int getId() {
return id;
} public String getCityName() {
return name;
} public void setCityName(String name) {
this.name = name;
} public String getDes() {
return des;
} public void setDes(String des) {
this.des = des;
}
}然后定义了一个sql mapper:<mapper namespace="data.database.mapper.CityMapper">
    <select id="getAllCity" resultMap="cityResult">
SELECT *
FROM cities 
    </select>
<resultMap type="City" id="cityResult">
<constructor>
<idArg column="id" javaType="int" />
</constructor>
<result property="cityName" column="city_name"></result>
</resultMap>
</mapper>但在执行这个getAllCity查询操作的时候。却出现了如下的异常:org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: org.apache.ibatis.reflection.ReflectionException: Error instantiating class data.bean.City with invalid types (Integer,) or values (1,). Cause: java.lang.NoSuchMethodException: data.bean.City.<init>(java.lang.Integer)
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### Cause: org.apache.ibatis.reflection.ReflectionException: Error instantiating class data.bean.City with invalid types (Integer,) or values (1,). Cause: java.lang.NoSuchMethodException: data.bean.City.<init>(java.lang.Integer)
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:8)于是我在City这个Bean里添加了一个构造函数: public City(Integer _ID){}于是一切正常了。哪个兄弟对mybatis熟悉些的,知道这是什么原因不?

解决方案 »

  1.   

    没有setId方法
    你加的方法是构造器注入
    还有一个就是set注入
      

  2.   

    正是因为不想加set方式注入ID。因为不想这个ID在运行的时候被随意改变。
    但是就算加了setId方法,也与public City(Integer _ID){}这个构造函数没关系。因为这个构造函数里我并没有给ID赋值,只是一个空方法。实际的情况是,即使在构造函数里没赋值的情况下id仍然可以被正常赋值。
    从异常来看,应该是myBatis在调用构造函数的时候出现异常了。
      

  3.   

    对MyBatis不甚了解,用得比较少,
    冒犯的问一句:是不是需要给个无参构造器啊
      

  4.   

    不是的。给无参构造函数还是会抛同样的错。只有给public City(Integer _ID){}这样的构造函数才会正常。