Mybatis There is no getter for property named 'X'

在嘗試使用mybatis的動態sql中遇到這麼一個問題,java

使用Mybatis查詢時,其參數能夠是基本數據類型或者像Integer和String這樣的簡單的數據對象,也能夠是複雜對象(通常是指JavaBean)或者map等,當使用基本數據類型的參數時,若這個參數的使用放在了判斷條件中,sql

<!-- mybatis 動態sql-->
<select id="findFruit" resultType="Fruit">
    SELECT * FROM tb_fruit
    WHERE name = 'helloworld'
    <if test="tyep != null">
        AND type = #{tyep }
    </if>
</select>

查詢,apache

@Test
public void test8837() throws SQLException {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    sqlSession.getConnection().setAutoCommit(true); //設置事務的自動提交
    List<Fruit> fruits = sqlSession.selectList(
        "com.usoft.mapper.FruitMapper.findFruit", null);
    List<Fruit> fruits2 = sqlSession.selectList(
        "com.usoft.mapper.FruitMapper.findFruit", 1);
    System.out.println(fruits.size());
    System.out.println(fruits2.size());
    sqlSession.close();
}

則會報以下錯誤,mybatis

org.apache.ibatis.exceptions.PersistenceException: app

### Error querying database.  Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'tyep' in 'class java.lang.Integer'ui

### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'tyep' in 'class java.lang.Integer'code

就是說 Integer 類中沒有type這個屬性,是啊 ,Integer 中原本就沒有type這個屬性啊,實際上是,在mybatis中,採用ONGL解析參數,因此會自動採用對象樹的形式獲取傳入的變量值。這裏傳入參數的類型爲 int ,其自動裝箱爲Integer,獲取type參數的值時,其實獲取的就是Integer的type屬性值。因此這樣的寫法是不對的。對象

應該改爲以下,事務

<!-- mybatis 動態sql-->
<select id="findFruit" resultType="Fruit">
    SELECT * FROM tb_fruit
    WHERE name = 'helloworld'
    <if test="_parameter != null">
        AND type = #{_parameter}
    </if>
</select>

這裏的 _parameter 代表這個參數的類型爲基本類型或基本類型的封裝類型。get

================END================

相關文章
相關標籤/搜索