MyBatis传入参数的实例代码
程序员文章站
2024-03-12 17:21:50
在mybatis的select、insert、update、delete这些元素中都提到了parametertype这个属性。mybatis现在可以使用的parameter...
在mybatis的select、insert、update、delete这些元素中都提到了parametertype这个属性。mybatis现在可以使用的parametertype有基本数据类型和java复杂数据类型
基本数据类型:包含int,string,date等。基本数据类型作为传参,只能传入一个。通过#{参数名} 即可获取传入的值
复杂数据类型:包含java实体类、map。通过#{属性名}或#{map的keyname}即可获取传入的值
基本数据类型参数示例:
根据班级id查询教师列表
xml文件
<select id="selectteacher" parametertype="int" resulttype="com.myapp.domain.teacher"> select * from teacher where c_id=#{id} </select>
java代码
list<teacher> tlist = teachermapper.selectteacher(2); for (teacher entitytemp : tlist) { system.out.println(entitytemp.tostring()); }
java实体类型参数示例:
<select id="selectteacher" parametertype="com.myapp.domain.teacher" resulttype="com.myapp.domain.teacher"> select * from teacher where c_id=#{id} </select>
java代码
teacher queryteacher=new teacher(); queryteacher.setid(2); list<teacher> tlist = teachermapper.selectteacher(queryteacher); for (teacher entitytemp : tlist) { system.out.println(entitytemp.tostring()); }
map参数示例:
<select id="selectteacher" parametertype="map" resulttype="com.myapp.domain.teacher"> select * from teacher where c_id=#{id} and sex=#{sex} </select>
java代码
map<string,string> map=new hasmap<string,string>(); map.put("id","2"); map.put("sex","男"); list<teacher> tlist = teachermapper.selectteacher(map); for (teacher entitytemp : tlist) { system.out.println(entitytemp.tostring()); }
另外mybatis还提供了一个使用注解来参入多个参数的方式。这种方式需要在接口的参数上添加@param注解
示例:
接口方法
public list<teacher> selectteacher(@param(value="id") string id,@param(value="sex") string sex);
xml文件
<select id="selectteacher" resulttype="com.myapp.domain.teacher"> select * from teacher where c_id=#{id} and sex=#{sex} </select>
测试代码
list<teacher> tlist = teachermapper.selectteacher("2","男"); for (teacher entitytemp : tlist) { system.out.println(entitytemp.tostring());
下面再给大家分享mybatis传参
1、当传参为list 时:
1.1 mapper接口中:
void updatecontactsisread(list<integer> logidlist);
1.2 mapper.xml 文件中:
<update id="updatecontactsisread"> update emaillog2 set isread = 1 where isread = 0 and logid in <foreach collection="list" item="logid" index="index" open="(" close=")" separator=","> #{logid,jdbctype=integer} </foreach> </update>
以上所述是小编给大家介绍的mybatis传入参数的实例代码,希望对大家有所帮助