前言
MyBatis作为一款持久层的框架,从最初的ibatis更名,经过五六年的发展更新,如今已经更新到了3.4.5版本。MyBatis通过简单的xml或注解配置,就能将接口和Java的对象映射成数据库的记录,避免了很多的手动配置,现已被越来越多的开发者使用。
刚开始使用的话,可能会有很多困惑:明明传递了值,为什么传递不到xml中?到底该用resultMap还是用resultType?如果我想返回String、Map、List等等,该如何写?在写了这么多MyBatis代码后,我总结了一下项目中常见的几种,供大家参考,如果想进一步了解,请参考官方文档:http://www.mybatis.org/mybatis-3/zh/index.html
干货图
接口和xml对应图表
高清图:http://img.blog.csdn.net/20170831064012748
干货图描述
在业务逻辑中,最常用的当属查询了,传递的值多样化,需要的返回值样式也不一样,但是等写好了回来再看时,发现也就那几种。
1. 参数类型:String,返回值类型:List
public List
getStudentByName(@Param(value="name") String name); select * from xxx where stu_name = #{name}
2. 参数类型:Map
public List
getStudents(Map params); select * from xxx where stu_name = #{name}
3. 参数类型:String,返回值类型:对象
public Student getStudentById(@Param(value="id") String id);
select * from xxx where id = #{id}
4. 参数类型:String,返回值类型:String
String queryUserIdByThirdParty(@Param("openId") String openId);
select user_id from sys_users where open_id=#{openId}
5. 参数类型:String,返回值类型:List
List
getUserIds(@Param("tenantId") String tenantId); select id from sys_users where tenant_id = #{tenantId};
6. 参数类型:String,返回值类型:Map
Map
getChargeSum(@Param(value = "uid") String uid); select sum(transaction_amount) as chargeSum from xxx where id = #{uid}
7. 参数类型:String,返回值类型:List
List
select * from xxxx where mw_account = #{account}
8. 参数类型:String,返回值类型:int
int deleteById(@Param(value = "id") String id, @Param(value = "uid") String uid);
delete from xxxx where id = #{id} and create_by = #{uid};
9. 参数类型:void,返回值类型:int
int deleteById(@Param(value = "id") String id, @Param(value = "uid") String uid);
delete from xxxx where id = #{id} and create_by = #{uid};
10. 参数类型:对象,返回值类型:int
int updateStuInfo(StudentInfo studentInfo);
update xxxx set stu_name = #{stuName}...
where id = #{id}
说明
1. 接口中的@Param注解指的是 org.apache.ibatis.annotations.Param,使用这个注解就相当于给一个参数起一个别名,在xml中可以直接使用这个别名。如果不使用这个注解,需要保证参数的名称和xml中property配置相同。
org.mybatis
mybatis
3.4.5
2. 在查询中,parameterType有时是可选的,但是resultMap或者resultType基本上都是需要的。
3. BaseResultMap指的是数据表和对象的映射关系,如:
...
4. 如果使用IDEA开发工具,可以下载Free MyBatis plugin插件,可以在xml和接口直接进行点击跟踪。
这次没有涉及到批量插入和复杂点继承关系查询,后续会更新。
閱讀更多 京京肚肚擼代碼 的文章