MyBatis学习总结(1)
1.1MyBatis的增删改查
1.添加
<!--int insertUser();--> |
2.删除
<!--int deleteUser();--> |
3.修改
<!--int updateUser();--> |
4.查询一个实体类
<!--User getUserById();--> |
5.查询集合
<!--List<User> getUserList();--> |
注意: |
1.2MyBatis获取参数值的两种方式(重点)
MyBatis获取参数值的两种方式:${}和#{} |
1.单个字面量类型的参数
若mapper接口中的方法参数为单个的字面量类型 |
<!-- User getUserByUsername(String username);--> |
2.多个字面量类型的参数
若mapper接口中的方法参数为多个时 |
<!-- User checkLogin(String username , String password);--> |
3.map集合类型的参数
若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中 |
4.实体类类型的参数
若mapper接口中的方法参数为实体类对象时 |
5.使用@Param标识参数
可以通过@Param注解标识mapper接口中的方法参数 |
6.总结
只需要记住第四种和第五种,有实体类可以接收数据,就用实体类接收,#{属性值},${}接受字符串和日期类时,手动加单引号。第五种,当没有实体类可以接收数据,用@Param,以@Param注解的value属性值为键,以参数为值;以param1,param2...为键,以参数为值,通过${}和#{}访问map集合的键就可以获取相对应的值,${}需要手动加单引号。 |
实体类接收,用#{} |
1.3MyBatis的各种查询功能
1.查询一个实体类对象
/** |
<!--User getUserById(@Param("id") int id);--> |
2.查询一个List集合
/** |
<!--List<User> getUserList();--> |
3.查询单个数据
/** |
<!--int getCount();--> |
4.查询一条数据为map集合
/** |
<!--Map<String, Object> getUserToMap(@Param("id") int id);--> |
5.查询多条数据为map集合
/** |
<!--Map<String, Object> getAllUserToMap();--> |
/** |
<!--Map<String, Object> getAllUserToMap();--> |
1.4特殊SQL的执行
1.模糊查询
/** |
<!--List<User> testMohu(@Param("mohu") String mohu); 推荐第三种写法--> |
2.批量删除
/** |
<!--int deleteMore(@Param("ids") String ids); 批量删除只能用${}--> |
3.动态设置表名
/** |
<!--List<User> getAllUser(@Param("tableName") String tableName);--> |
4.添加功能获取自增的主键
/** |
<!--int insertUser(User user);--> |
1.5自定义映射resultMap
1.resultMap处理字段和属性的映射关系
若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射 |
<!-- |
若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性 |
2.多对一映射处理
2.1级联方式处理映射关系
<resultMap id="empDeptMap" type="Emp"> |
2.2使用association处理映射关系
<resultMap id="empDeptMap" type="Emp"> |
2.3分步查询
2.3.1查询员工信息
/** |
<resultMap id="empDeptStepMap" type="Emp"> |
2.3.2根据员工所对应的部门id查询部门信息
/** |
<!--Dept getEmpDeptByStep(@Param("did") int did);--> |
3.一对多映射处理
3.1使用collection处理映射关系
/** |
<resultMap id="deptEmpMap" type="Dept"> |
3.2分步查询
3.2.1查询部门信息
/** |
<resultMap id="deptEmpStep" type="Dept"> |
3.2.2根据部门id查询部门中的所有员工
/** |
<!--List<Emp> getEmpListByDid(@Param("did") int did);--> |
分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息: |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小白条的个人博客!