mybatis学习记录 (二) 映射文件

1. 参数处理

在上个博客中,我们可以看到UserMapper.java和UserMapper.xml文件中有这相应的对应,在这里我先将这两个文件的代码展示出来。

1.1 文件展示

UserMapper.java

package com.jt;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

public interface  UserMapper {
   public User selectUser(int id);//单个参数传递
   public User  selectUserByIdAndName(@Param("id") Integer id,@Param("username") String username);// 多个参数传递
   public User  selectUserByIdAndNameUseMap(Map map);//多个参数传递

   public Integer insertUser(User user);
   public boolean updateUser(User user);
   public Integer deleteUserById(int id);
}

UserMapper.xml文件




    
    
    
    
        insert into test01 (username,password) values(#{username},#{password})
    
    
        update test01 set username=#{username} where id=#{id}
    
    
        delete from test01 where id=#{id}
    

1.2 文件分析

在UserMapper.java接口文件中,传递的参数有,单个参数,多个参数的情况。

1.2.1 单个参数

直接使用#{}或者${}去接收参数即可

public User selectUser(int id);//单个参数传递

1.2.2 多个参数参数

总结 #{}或者${}这种方式取值,本质是在一个Map对象中根据key值去获取参数值。
(1)使用@Param定义在xml文件中获取参数的key值

   public User  selectUserByIdAndName(@Param("id") Integer id,@Param("username") String username);// 多个参数传递
    

(2)或者不用@Param,在xml文件中使用#{param1}这种形式来获取相应参数的值

   public User  selectUserByIdAndName(Integer id,String username);// 多个参数传递
    

(3)使用pojo类来传递参数

  public Integer insertUser(User user);
    
        insert into test01 (username,password) values(#{username},#{password})
    

(4)使用map来传递参数

   public User  selectUserByIdAndNameUseMap(Map map);//多个参数传递
    

1.2.3 #{}和${}的区别

{} 使用了预编译

${}没有使用预编译,安全性相对比较低。
下图可以清晰的解释两者的区别。

mybatis学习记录 (二) 映射文件_第1张图片

你可能感兴趣的:(mybatis)