javaspringthymeleafh2spring-el

Displaying JPA Entity table data to thymeleaf view


I have a JPA Entity table with id and name column. I want to display the name values to the thymeleaf view. Right now I am able to see the Entity object in the view but not the column values for name. Here's how I created the table and defined getters and setters:

@Entity
@Table(name = "Book")
public class Book extends AbstractPersistable<Long> {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name = "name")
private String name;

public Long getID() {
    return this.id;
}

public String getContent() {
    return this.name;
}

public void setID (Long id) {
    this.id = id;
}

public void setContent (String name) {
    this.name = name;
    }
}

From the controller this is how I am trying to set the content:

@Controller
@RequestMapping("/")
public class BookController {

@Autowired
private BookRepository bookRepository;

@RequestMapping("/addBook")
@ResponseBody
public String addBook(@RequestParam("name") String name) {
    Book book = new Book();

    book.setContent(name);
    bookRepository.save(book);
    return name;

}

@RequestMapping(value = "book", method = RequestMethod.GET)
    public String books(Model model) {
    model.addAttribute("books", bookRepository.findAll());
    return "book";
    } 

}

The thymeleaf view template:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:th="http://www.thymeleaf.org"      
  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    <head lang="en">
        <meta charset="UTF-8" />
        <title>Books</title>
    </head>
    <body>
        <h1>Books Database</h1>
        <ul th:each="book : ${books}">
            <li th:text="${book.name}"></li>
        </ul>                
    </body>
</html>

When I add new books from the addBook page and visit the book page to see the book names then I get this error:

Exception evaluating SpringEL expression: "book.name". In the IDE console the error found as: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'name' cannot be found on object of type 'sec.book.BookNames.

What could be wrong?

In the view if i use th:text="${book} then a list of Entity objects appears like this for each row from the table. This is what is shown:

Entity of type sec.helloworld.Book with id: null.

I just want the book names to show up not the objects. How am I supposed to do that?


Solution

  • Yoor getter for name must be named getName() in order to be found by ExpressionLanguage(SpEL = Spring Expresion Language). The setter should be setName, too.