zoukankan      html  css  js  c++  java
  • Java -- MyBatis学习笔记6、参数传递

    1、parameterType

    接口中方法参数的类型,类型的完全限定名或别名。这个属性是可选的,因为MyBatis可以推断出具体传入语句的参数.

    • 比如dao层接口中有一个查询单个对象的方法:
    public UserInfo selectUser(int id);
    
    • 对应的mapper映射文件如下:
    <select id="selectUser" parameterType="int" resultType="com.rg.entity.UserInfo">
         select * from UserInfo where id = #{id}
    </select>
    

    这里边使用的int,而不是全限定名称、是因为mybatis里给每个类型都定义了别名、可以查阅相关文档进行对照。

    2、传递简单参数

    Dao层接口中方法的参数只有一个简单类型、java基本类型和 String,在mapper文件中的标签中的SQL语句使用占位符#{任意字符}即可接收、和方法的参数名无关。

    • 还以上边代码为例、将mapper文件中的SQL语句中的#{id}改为#{userid}也是可以的,如下:
    <select id="selectUser" parameterType="int" resultType="com.rg.entity.UserInfo">
        select * from UserInfo where id = #{userid}
    </select>
    

    3、传递多个参数-Param

    当Dao接口方法多个参数、推荐@Param注解传参、在每个参数前边添加@Param(“自定义参数名”)、就相当于给每个参数定义别名、那么在mapper文件中就就这样使用:#{自定义参数名}

    • Dao层接口方法:
    public UserInfo selectUser(@Param("uid") int id, @Param("uname") String name);
    
    • mapper映射文件:
    <select id="selectUser" resultType="com.rg.entity.UserInfo">
         select * from UserInfo where id = #{uid} and Name=#{uname}
    </select>
    

    4、传递多个参数-对象

    使用Java对象传递参数、在mapper文件SQL语句占位符中就写对象里边属性名称就行。

    • 创建实体类、用来传递参数
    public class QueryParam
    {
        private int userId;
        private String userName;
        //get set toString....
    }
    
    • Dao接口中方法
    public UserInfo selectUser(QueryParam queryParam);
    
    • mapper映射文件
    <select id="selectUser" resultType="com.rg.entity.UserInfo">
        select * from UserInfo where id = #{userId} and Name=#{userName}
    </select>
    

    以上就是在MyBatis中最常用的参数传递的方式了。当然、还有其它方式,比如按位置传递、使用map传递等等、不过这都不常用、掌握这几种常用的就行了。

  • 相关阅读:
    hbase coprocessor 二级索引
    文档:ubuntu安装.pdf
    Python过滤敏感词汇
    nginx 对django项目的部署
    ZooKeeper 的常用操作方法
    Python操作reids
    教你为nginx 配置ssl 证书!
    单线程多任务异步爬虫
    go语言入门之环境的搭建
    关于csrf跨站请求伪造攻击原理,与csrftoken防范原理
  • 原文地址:https://www.cnblogs.com/dcy521/p/14746773.html
Copyright © 2011-2022 走看看