Java-开发技术框架-Mybatis基本用法 --- 数据输入

1、Mybatis总体机制概括

2、概念说明 

这里数据输入具体是指上层方法(例如 Service 方法)调用 Mapper 接口时,数据传入的形式。

  • 简单类型:只包含一个值的数据类型

    • 基本数据类型:int、byte、short、double、……
    • 基本数据类型的包装类型:Integer、Character、Double、……
    • 字符串类型:String
  • 复杂类型:包含多个值的数据类型

    • 实体类类型:Employee、Department、……
    • 集合类型:List、Set、Map、……
    • 数组类型:int[]、String[]、……
    • 复合类型:List<Employee>、实体类中包含集合……

3、单个简单类型参数

①Mapper接口中抽象方法的声明

Employee selectEmployee(Integer empId);

②SQL语句

<select id="selectEmployee" resultType="com.atguigu.mybatis.entity.Employee">
    select emp_id empId,emp_name empName,emp_salary empSalary from t_emp where emp_id=#{empId}
</select>

4、实体类类型参数

①Mapper接口中抽象方法的声明

int insertEmployee(Employee employee);

②SQL语句

<insert id="insertEmployee">
    insert into t_emp(emp_name,emp_salary) values(#{empName},#{empSalary})
</insert>

③对应关系

④结论

Mybatis会根据 #{ } 中传入的数据,加工成 getXxx( ) 方法,通过反射在实体类对象中调用这个方法,从而获取到对应的数据。填充到 #{ } 这个位置。

5、零散的简单类型数据

①Mapper接口中抽象方法的声明

int updateEmployee(@Param("empId") Integer empId,@Param("empSalary") Double empSalary);

②SQL语句

    <update id="updateEmployee">
        update t_emp set emp_salary=#{empSalary} where emp_id=#{empId}
    </update>

③对应关系

6、Map类型参数

①Mapper接口中抽象方法的声明

int updateEmployeeByMap(Map<String, Object> paramMap);

②SQL语句

    <update id="updateEmployeeByMap">
        update t_emp set emp_salary=#{empSalaryKey} where emp_id=#{empIdKey}
    </update>

③junit测试


@Test
public void testUpdateEmpNameByMap() {
    SqlSession session = sessionFactory.openSession();
    
    EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
    
    Map<String, Object> paramMap = new HashMap<>();
    
    paramMap.put("empSalaryKey", 999.99);
    paramMap.put("empIdKey", 5);
    
    int result = mapper.updateEmployeeByMap(paramMap);
    
    System.out.println("result = " + result);
    
    session.commit();
    
    session.close();
}

④对应关系

  #{  }  中写 Map<key,value> 中的 key 

⑤使用场景

有很多零散的参数需要传递,但是没有对应的实体类类型可以使用。使用@Param注解一个一个传入又太麻烦了。所以都封装到Map中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值