您的位置:首页 > 其它

【MyBatis学习05】传入参数parameterType

2017-03-18 23:52 501 查看
本文博客地址:http://blog.csdn.net/soonfly/article/details/63373362 (转载请注明出处)

在前面的mapper.xml的select、insert、update、delete这些元素中,我们已接触了传入参数,并通过parameterType指定传入参数的类型。注意不要和parameterMap混淆了。(parameterMap几乎很少场景下用了)



MyBatis可以使用的parameterType有基本数据类型和Java复杂数据类型。

复杂数据类型包含Java实体类、Map等。

一、基本数据类型:

包含int,String,Date等。基本数据类型作为传参,只能传入一个。通过#{参数名} 即可获取传入的值。

<delete id="delete" parameterType="int">
delete from user where id=#{id}
</delete>


java代码:

usermapper.delete(1);
session.commit();/*对写操作进行提交*/


其实这里的”参数名”可以是任意的。因为JAVA反射只能获取方法参数的类型,但无从得知方法参数的名字的

上面这个例子把#{id}换成#{di},一样运行。当然为了便于阅读代码,还是用#{id}。

二、Map类型

在基本类型中,我们只能传入一个参数。

如果要传入多个参数怎么办?比如要查询某个价格区间的商品,那么就需要构建minPrice、maxPrice两个参数,这时可以用到Map。

通过#{map的KeyName}即可获取传入的值。

<select id="searchByPrice" parameterType="Map" resultType="Product">
<![CDATA[select * from Product where price >= #{minPrice} and price <= #{maxPrice} ]]>
</select>


java调用:

SqlSession session = SqlSessionAssist.getSession();

Map<String, Double> pricemap=new HashMap<String,Double>();
pricemap.put("minPrice", 1000.00);
pricemap.put("maxPrice", 6000.00);

List<Product> tmpuser=session.selectList("twm.mybatisdemo.mapper.ProductMapper.searchByPrice", pricemap);
System.out.println(tmpuser.size());
session.close();


参数传递时,一定要保证sql语句中的#{minPrice}和map中的key值一样,大小写敏感。否则会报参数错误。

正是因为这个原因,所以最好是用Java实体作为传参

三、Java实体类型

通过
#{属性名}
即可获取传入的值。这跟map很类似。

这里要说的是内部类的传参方式 。如果有内部类存在,则用
#{内部类对象名.属性名}
获取传入值。

class productVo {
Product pro;

public Product getProduct() {
return pro;
}
public void setProduct(Product product) {
this.pro = product;
}
}


<select id="searchByPrice" parameterType="productVo" resultType="Product">
<![CDATA[select * from Product where price >= #{pro.minPrice} and price <= #{pro.maxPrice} ]]>
</select>


本文博客地址:http://blog.csdn.net/soonfly/article/details/63373362 (转载请注明出处)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: