Mybatis 增删改查等操作的返回值
https://www.dandelioncloud.cn/article/details/1471626023791058946
之前一篇文章 mybatis 传递参数的7种方法 讲了mybatis中传递入参的7中方式,这节讲下增删改查等操作的返回值都代表什么意思,以及怎么使用这些返回值
1.更新 update
update: 返回值为匹配数据库的条数(不论最终是否对数据进行了修改,只要某条记录符合匹配条件,返回值就加1)
2.插入 insert
insert:如果成功返回值为插入数据库的条数,失败返回的是exception,所以需要对异常进行处理
public int insertDept(Department department)
{
try{
return departmentMapper.insertAutoId(department);
}catch (Exception e )
{
return -1;
}
}
@ApiOperation(value = “新增部门”)
@PostMapping(“new”)
public ResultMsg newDepartment(@RequestBody Department department) {
department.setId(idWorker.nextId());
int result = departmentService.insertDept(department);
return ResultMsg.getStrMsg(result > 0 ? “SUCCESS” : “FAILED”);
}
3.删除 delete
delete:返回值为删除的数据条数
- 查询 select
四种基本操作中,以查询操作的返回值最为多样化
Mybatis中,通过resultType或resultMap指定返回值
3.1返回一般数据类型
即返回Java基本的数据类型,如String Long int
mapper
String getDeptName(Long id);
xml
mapper
Department getDeptById(Long id);
xml
resultMap方式:当javabean和数据库表字段不一致时,可使用resultMap指定返回结果类型;一个Mapper文件可定义多个resultMap
在一个查询中,resultType跟resultMap不能同时存在
3.3返回List类型
当返回数据有多条时,可通过List方式返回
mapper
List selectAll();
xml
1.返回单条数据,map对应表中字段
Map getDeptAsMap(Long id);
select
*
from department
where id = #{id,jdbcType=BIGINT}
2.返回多条数据
以Map形式返回多条数据,map中每一条记录对应一条查询记录,(该方式与List返回值类似,不过是数据的组织方式不同而已),这里需要指定使用哪个属性作为Map主键
mapper
@MapKey(“id”) //指定Map的主键为返回结果的id
Map getDeptAsMaps();
xml
controller
@ApiOperation(value = “返回JSONObject”)
@PostMapping(“findJSONObject”)
public ResultMsg findJSONObject( )
{
return ResultMsg.getMsg(employeeMapper.findJSONResult());
}
mapper
JSONArray findJSONResult();
xml
下节我讲下Mybatis中如何实现一对一和一对多的查询操作
一对一查询 assocation
一对多查询collection
最下边为mybatis组件配置文件的部分配置
排除默认的datasource类配置,采用上边截图中自己定义类的配置