zoukankan      html  css  js  c++  java
  • Mybatis接口中传递多个参数

    1.接口

    public interface MemberMapper {
    
        public boolean insertMember(Members member);
    
        public Members selectMember(Integer id, String name);
    
    }

    2.配置文件

    不能这样写,通过查看mybatis源码后发现,单个参数mybatis不会做处理,多个参数会将传递过来的参数封装成一个map集合,key是从param1开始一直到paramN,而value是我们传递过来的值

    以下这样取值是取不到的,如果还想这样取值,可以用注解的方式,如下:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.dao.MemberMapper">
    
      <select id="selectMember" resultType="members">
        select * from members where id=#{id} and member_name=#{member_name}  
      </select>
      
    </mapper>

    注解方式取值(推荐)

    public interface MemberMapper {
    
        public boolean insertMember(Members member);
    
        public Members selectMember(@Param("id") Integer id, @Param("member_name") String name);
    
    }

    还可以这样取值(不推荐)

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.dao.MemberMapper">
    
      <select id="selectMember" resultType="members">
        select * from members where id=#{param1} and member_name=#{param2}  
      </select>
      
    </mapper>

    #######  如果传入的参数正好跟业务pojo类有关,可以不必传入零散参数,直接传入pojo类即可

    #######  如果传入的参数与跟pojo类不相关,可以将参数直接封装成一个Map(不经常使用的接口可以这样做)

    #######  如果接口经常被使用,而且跟pojo不相关的话,可以使用自定义TO对象来传递

    照着别人搭好的框架写代码容易,如果不一探究竟,噢,原来还可以这样写~哈哈

  • 相关阅读:
    62. Unique Paths
    24. Swap Nodes in Pairs
    83. Remove Duplicates from Sorted List
    21. Merge Two Sorted Lists
    141. Linked List Cycle
    268. Missing Number
    191. Number of 1 Bits
    231. Power of Two
    9. Palindrome Number
    88. Merge Sorted Array
  • 原文地址:https://www.cnblogs.com/zhangjianbing/p/8320988.html
Copyright © 2011-2022 走看看