天天看點

Springdata JPA(2.0.6版本)中相似但不同的東西的方法,findById和getOne,findOneById

findById、getOne和findOneById的差別

代碼示例

@GetMapping("/getOne")
  public ResultBean getOne(Long id) {
    return ResultBean.ok(stu2Service.getOne(id));
  }      
@GetMapping("/findById")
  public ResultBean findById(Long id) {
    return ResultBean.ok(stu2Service.findById(id));
  }      
@GetMapping("/findOneById")
  public ResultBean findOneById(Long id) {
    return ResultBean.ok(stu2Service.findOneById(id));
  }      
  1. 傳回對象不同
public Optional<T> findById(ID id); 傳回的是Optional對象,通過.get()可擷取到對象
public T getOne(ID id); 不是直接傳回的對象,但此方法可以擷取對象的相關屬性值
Stu2 findOneById(Long id);  根據命名規則中自定義實作,可直接傳回到對象      
  1. 對空值異常的處理不同,此處模拟的是如果Id在資料庫中不存在時的異常
findById
          No value present] with root cause      
getOne
  Unable to find com.aust.first.entity.Stu2 with id 20      
findOneById,沒有異常出現      
  1. SQL語句不同
findById
          SELECT
  stu2x0_.id_ AS id_1_1_0_,
  stu2x0_.admission_time AS admissio2_1_0_,
  stu2x0_.age_ AS age_3_1_0_,
  stu2x0_.created_by AS created_4_1_0_,
  stu2x0_.hobbies_ AS hobbies_5_1_0_,
  stu2x0_.name_ AS name_6_1_0_,
  stu2x0_.phone_ AS phone_7_1_0_,
  stu2x0_.sid_ AS sid_8_1_0_,
  stu2x0_.summary_ AS summary_9_1_0_
FROM
  ls_stu2 stu2x0_
WHERE
  stu2x0_.id_ =?      
getOne          
SELECT
  stu2x0_.id_ AS id_1_1_0_,
  stu2x0_.admission_time AS admissio2_1_0_,
  stu2x0_.age_ AS age_3_1_0_,
  stu2x0_.created_by AS created_4_1_0_,
  stu2x0_.hobbies_ AS hobbies_5_1_0_,
  stu2x0_.name_ AS name_6_1_0_,
  stu2x0_.phone_ AS phone_7_1_0_,
  stu2x0_.sid_ AS sid_8_1_0_,
  stu2x0_.summary_ AS summary_9_1_0_
FROM
  ls_stu2 stu2x0_
WHERE
  stu2x0_.id_ =?      
findOneById         
SELECT
  stu2x0_.id_ AS id_1_1_,
  stu2x0_.admission_time AS admissio2_1_,
  stu2x0_.age_ AS age_3_1_,
  stu2x0_.created_by AS created_4_1_,
  stu2x0_.hobbies_ AS hobbies_5_1_,
  stu2x0_.name_ AS name_6_1_,
  stu2x0_.phone_ AS phone_7_1_,
  stu2x0_.sid_ AS sid_8_1_,
  stu2x0_.summary_ AS summary_9_1_
FROM
  ls_stu2 stu2x0_
WHERE
  stu2x0_.id_ =?