dao层的新增和修改等的整数类型返回值需要判断吗?需要吗,需要吗
不需要
一般会判断,用于判断是否执行成功
正常来讲是需要判断的, 只有 大于 0 了,才说明的确新增了数据,或 修改了数据
public int updateUser(User user) {
// 若用户参数不合法,直接return
if (user == null || user.getId() == null) return 0;
// 更新用户信息
String sql = "update user set name=? where id=?";
int rows = jdbcTemplate.update(sql, user.getName(), user.getId());
// 这里加一个判断,确保更新行数为1,否则抛出异常
if (rows != 1) {
throw new RuntimeException("更新用户失败!");
}
return rows;
}
在这个方法中,由于内部有参数判断逻辑,并且更新行数期望为1,所以返回值判断是很有必要的。
如果没有任何判断,直接执行更新语句:
public int updateUser(User user) {
String sql = "update user set name=? where id=?";
return jdbcTemplate.update(sql, user.getName(), user.getId());
}
那么返回值判断就不是必须的,返回值不为0即表示更新成功。
不知道你这个问题是否已经解决, 如果还没有解决的话: /**
* 根据手机号码查询该用户下所有的信息
* @param phoneNumber
* @throws Exception
* @return
*/
@Select("SELECT * FROM record WHERE phoneNumber = #{phoneNumber}")
@Results({
@Result(property = "uuid",column = "id",id = true),
@Result(property = "category",column = "category"),
@Result(property = "content",column = "content"),
@Result(property = "money",column = "money"),
@Result(property = "status",column = "status"),
@Result(property = "date",column = "date")
})
List<Record> findAllByPhoneNumber(String phoneNumber) throws Exception;
数据库中的record的id字段对应了Record类中的uuid属性,为什么直接id对应id呢?原因我上篇文章也说过了,就是客户端的SQLite中id只能是int型的,所以用加了个uuid属性。
在Java的DAO层中,执行新增、修改等操作后得到的整数类型返回值需要进行判断,具体步骤如下:
示例代码:
public interface IEmployeeDao {
/**
* 新增员工
*
* @param employee 员工信息
* @return 受影响的数据库记录条数
*/
public int addEmployee(Employee employee);
/**
* 修改员工信息
*
* @param employee 员工信息
* @return 受影响的数据库记录条数
*/
public int updateEmployee(Employee employee);
}
public class EmployeeDaoImpl implements IEmployeeDao {
@Override
public int addEmployee(Employee employee) {
int result = 0;
// TODO: 执行新增员工操作
// result = ...;
if (result <= 0) {
throw new RuntimeException("新增员工失败");
}
// TODO: 获取生成的主键值
// ...
return result;
}
@Override
public int updateEmployee(Employee employee) {
int result = 0;
// TODO: 执行修改员工操作
// result = ...;
if (result <= 0) {
throw new RuntimeException("修改员工信息失败");
}
return result;
}
}
非必须。
我举几个例子你体会一下:
1.业务或页面明确要求0行时,返回新增或修改失败的要判断;
2.接口中后续操作不依赖本次新增或修改(或者没有后续操作),可以不判(接口加上事务即可);接口后续操作依赖本次修改的,需要判断(a.如:新增或修改后,然后需要查询指定数据;b.如:新增两条主从表数据,有外键关系,主表新增成功后,才能新增从表,当然也可以不判,直接抛异常也OK);
可以说更多的都是业务或页面上的体验需要判断,否则交给事务和异常处理机制来处理即可。