MyBatis方法传入参数的获取的方式

MyBatis方法传入参数的获取

1.通过索引获取

1.#{arg0},#{arg1}的形式,方法参数的传入存放在一个数组中
2.#{param1},#{param2}.....依次获得方法中的参数

//通过#{arg0}的形式或的方法传入参数的第一个参数
    public User login(String name,String password);
    //通过#{param1}的形式或的方法传入参数的第一个参数
    public User login1(String name,String password);

<select id="login" resultType="user">
        select * from t_user where name =#{arg0} and password =#{arg1};
    </select>
    <select id="login1" resultType="user">
     select * from t_user where name =#{param1} and password =#{param2};
    </select>

2.通过注解给方法参数起别名

@Param(参数别名)

//通过注解为方法的参数起别名用于获取
    public User login2(@Param("name") String name,@Param("password") String password);

 <select id="login2" resultType="user">
     select * from t_user where name =#{name} and password =#{password};
    </select>

3.通过实例化对象获得方法参数

方法的参数类型是一个实例化对象,通过#{属性名}获得对应的属性值

 <select id="login3" resultType="user">
     select * from t_user where name =#{name} and password =#{password};
    </select>

//传入一个实例化对象通过#{属性名}的形式获得对应的值
    public User login3(User user);

4.通过传入一个map对象获得方法参数

方法的参数数据类型是Map<String,Object>通过map的key值获得对应的value值

//传入一个map对象,通过#{key值}获得对应的value值
    public User login4(Map<String,Object> map);

  <select id="login4" resultType="user">
     select * from t_user where name =#{n} and password =#{p};
    </select>

总结:

方法参数少,可以用注解的方法,如果参数多余5个就要想办法将其封装成一个对象,或者封装成一个map进行数据的传递
MyBatis获取参数的几种方式有: 1. 使用@Param注解:在Mapper接口的方法参数列表中使用@Param注解,可以为参数一个名字,方便在SQL语句中引用。 例如: ``` @Select("SELECT * FROM user WHERE id = #{id}") User getUserById(@Param("id") int userId); ``` 2. 使用Map类型参数:在Mapper接口的方法参数列表中使用Map类型参数,可以将所有参数封装到Map中,通过键值对的方式传递参数。 例如: ``` @Select("SELECT * FROM user WHERE id = #{id} AND name = #{name}") User getUserByIdAndName(Map<String, Object> paramMap); ``` 3. 使用POJO类型参数:在Mapper接口的方法参数列表中使用自定义的POJO类型参数,可以将参数封装到一个对象中,通过对象的属性名来引用参数。 例如: ``` @Insert("INSERT INTO user (id, name, age) VALUES (#{id}, #{name}, #{age})") int addUser(User user); ``` 4. 使用数组类型参数:在Mapper接口的方法参数列表中使用数组类型参数,可以将多个参数封装到一个数组中,通过数组下标的方式来引用参数。 例如: ``` @Select("SELECT * FROM user WHERE id IN (#{ids})") List<User> getUsersByIds(@Param("ids") int[] ids); ``` 5. 使用List类型参数:在Mapper接口的方法参数列表中使用List类型参数,可以将多个参数封装到一个List中,通过List中元素的位置来引用参数。 例如: ``` @Select("SELECT * FROM user WHERE id IN (#{ids})") List<User> getUsersByIds(List<Integer> ids); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值