加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

MyBatis传入参数的实例代码

发布时间:2020-12-14 19:49:52 所属栏目:Java 来源:网络整理
导读:在MyBatis的select、insert、update、delete这些元素中都提到了parameterType这个属性。MyBatis现在可以使用的parameterType有基本数据类型和JAVA复杂数据类型 基本数据类型:包含int,String,Date等。基本数据类型作为传参,只能传入一个。通过#{参数名} 即

在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传入参数的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!

您可能感兴趣的文章:

  • MyBatis传入集合 list 数组 map参数的写法
  • mybatis动态插入list传入List参数的实例代码
  • MyBatis中传入参数parameterType类型详解

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读