[問題]spring boot 報錯 NumberFormatException

作者: think12381   2019-12-12 22:32:57
請問一下各位大大 我目前正在學習Java spring boot
開發環境是採 用 idea
目的是要採用網頁去DB裡面撈資料出來
都會產生以下錯誤
Failed to convert value of type 'java.lang.String' to required type 'long';
nested exception is java.lang.NumberFormatException: For input string: "books"
看起來是說 自串不能轉long
但是我這樣要怎麼對到 html去
google許久還是查不到解法
請教各位大神
謝謝
以下是局部代碼
實體
===========================================
@Entity
public class Book2 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private int status;
private String author;
private String description;
===============================================
controller
@GetMapping("/booklist/{id}")
public String ListBook(@PathVariable("id") long id, Model model){
Optional<Book2> book2 = bookService.getOne(id);
if(book2 == null){
book2 = Optional.of(new Book2());
}
model.addAttribute("book", book2);
System.out.println(book2.get().getName()+ " "
+
book2.get().getId() + " "+
book2.get().getAuthor()+ " "+
book2.get().getDescription()+ " "+
book2.get().getStatus());
return "books";
=============================================================================
book repository
public interface BookRepository extends JpaRepository<Book2,Long> {
==============================================================================
service
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
===========================================================================
books.html
<body>
<div class = "container" style="max-width: 700px">
<h2 class = "page-header" style="margin-top: 50px">書單內容</h2>
<div class="well">
<p>
<strong> 作者 </strong>
<span th:text = "${book.author}"> bb
</span>
</p>
<p>
<strong> 描述 </strong>
<span th:text = "${book.description}"> cc </span>
</p>
<p>
<strong> 書名 </strong>
<span th:text = "${book.name}"> aa </span>
</p>
<p>
<strong> 狀態 </strong>
<span th:text = "${book.status}"> dd </span>
</p>
</div>
</div>
作者: ssccg (23)   2019-12-12 23:09:00
你是連什麼網址?
作者: think12381   2019-12-13 06:57:00
localhost:8080/booklist/44是我在db要抓的資料
作者: kohmiho (kohmiho)   2019-12-13 08:20:00
感覺像dbo 欄位沒對準
作者: ssccg (23)   2019-12-13 09:19:00
你是不是用成@RestController?
作者: think12381   2019-12-13 09:48:00
entity 欄位 順序 要一致?
作者: tw11509 (John-117)   2019-12-13 11:11:00
有stack的話,一起給出來,比較好幫你確認問題在哪裡而且你book2 == null寫法有問題,已經用optional了,先去看看optional的用法你放入model的是optional物件,不是book2物件,要先從optional去get出來你的pathvariable應該不是帶入books吧
作者: bloodrance (血色蘭斯(角度))   2019-12-24 16:24:00
.findById(id).orElse(null); < Service那邊要寫個沒記錯當時我用Spring 2.0看1.5的教學時發生過不過你的寫法我還是覺得怪詭異的 spring boot版本是?
作者: chi972121 (沈默之語)   2019-12-25 20:57:00
Optional有isPeesent*isPresent
作者: wxv1990 (人生活著要快樂!)   2018-03-08 15:58:00
book2.isEmpty

Links booklink

Contact Us: admin [ a t ] ucptt.com