在尝试使用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================