码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis的 传入基本类型注意点

时间:2015-11-04 11:38:14      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:



使用Mybatis查询时,其参数可以是基本数据类型或者像Integer和String这样的简单的数据对象,也可以是复杂对象(JavaBean)或者map等,

当使用基本数据类型的参数时,若这个参数的使用放在了判断条件中

<!-- mybatis 动态sql-->
<select id="findFruit" resultType="Fruit">
    SELECT * FROM tb_fruit
    WHERE name = ‘helloworld‘
    <if test="tyept != null">
        AND type = #{typet }
    </if>
</select>



查询,
@Test
public void test() 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();
}



则会报如下错误


org.apache.ibatis.exceptions.PersistenceException: 

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

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

就是说 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  表明这个参数的类型为 基本类型或基本类型的封装类型。






mybatis的 传入基本类型注意点

标签:

原文地址:http://my.oschina.net/exit/blog/525687

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!