Search code examples
javaspring-bootspring-mvcentitythymeleaf

Spring MVC / Thymeleaf - Null values not carrying over to model


I am having some trouble with Thymeleaf and Spring MVC. I have an entity class that is managed by a repository connected to a SQL database.

In my controller, I am adding a list of returned entities to my Model and trying to access these in my template. The problem is, when one of the fields of that entity is null, when trying to access that field it returns a SpEL error in the following format.

Exception evaluating SpringEL expression: "entity.phoneNumber" (template: "index" - line 13, col 17)

Like I mentioned previously, this ONLY happens when one of the fields of the Entity is null. I tried using the safe navigation operator like this...

entity?.phoneNumber

But it is the attribute that is null, not the entity itself.

I have also tried using something like this, but this also returns an error as it can't even find the attribute to see if it is null.

<span th:if="${entity.phoneNumber != null}" th:text="${entity.phoneNumber}">Phone Number</span>

The controller looks like this.

@Controller
public class IndexController {

@Autowired
CustomerService customerService;

@GetMapping
public String index(Model model) {
        List<ActiveCustomersEntity> entities = customerService.getAllCustomers();
        model.addAttribute("entities", entities);
        return "index";
    }
}

Now my template looks like this.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>

<body>
    <table>
        <tr th:each="entity : ${entities}">
            <td th:text="${entity.customerFormattedNm}">Customer Name</td>
            <td th:text="${entity.accountStatusCd}">Account Status Code</td>
        </tr>
    </table>
</body>

</html>

I have checked repeatedly for mis-spellings. When I only look at attributes that are guaranteed to have a value, everything works as intended. It is only attributes that have a chance to be null that cause issues.

Any help would be appreciated!


Solution

  • Providing an update since I figured out what was causing this. The entity class has getters which use the trim() function to remove the trailing whitespace from the database since it is using char instead of varchar. Null values can't be trimmed, so I simply had to change my getters to account for null values.

    return phoneNumber == null ? null : phoneNumber.trim();