初學SpringBoot 易踩雷區與拆彈指南

踩雷地圖持續更新中

Louis Chang
2 min readMar 17, 2021
Photo by Tamanna Rumee on Unsplash

Maven installation

MySQL No permission

MySQL Error: : ‘Access denied for user ‘root’@’localhost’

-> Find my.cnf and revise it (/usr/local/etc/my.cnf)

find /usr/local/ -iname "mysql"

Spring Data JPA (超級大雷)

出現Bean 相關error 的話可以檢查的地方(之後有遇到不一樣的會再新增上來):
1. Controller 名稱是否重複
2. 有些Class 的註解是否忘了加(例如Service 之類的)
3. 若是Repository 無法Autowired 的話,則要確認執行的Class 跟Repository 是否在同一個package 下

版本問題

Thymeleaf

@NotBlank

函式新舊寫法

Spring Data JPA — Select

// Old 
public Book findOne(long id) {
return bookRepository.findOne(id);
}
// New
public Book findOne(long id) {
return bookRepository.findById(id).orElse(null);
}

Spring Data JPA — Delete

// Old
public void delete(long id) {
bookRepository.delete(id);
}
// New
public void delete(long id) {
bookRepository.deleteById(id);
}

Sort

public Page<Book> findAllByPage() {
// Sort sort = new Sort(Sort.Direction.DESC, "id"); OLD
Sort sort = Sort.by(Sort.Direction.DESC, "id");
// Pageable pageable = new PageRequest(1, 5); OLD
Pageable pageable = PageRequest.of(1, 5, sort);
return bookRepository.findAll(pageable);
}
//Sort sort = new Sort(Sort.Direction.DESC, "id");
Sort sort = Sort.by(Sort.Direction.DESC, "id");
//Pageable pageable = new PageRequest(1, 5);
Pageable pageable = PageRequest.of(1, 5, sort);
return bookRepository.findAll(pageable);
}

--

--