【发布时间】:2021-02-22 17:18:25
【问题描述】:
我正在使用Spring Boot 和ThymeLeaf 发送电子邮件。在电子邮件模板中,我需要为bottle 检索相关的product 实体,但是当我尝试像这样${bottle.product.name} 检索它时,我一直收到错误消息。从相关的product 实体获取name 的正确方法是什么?
这是我得到的例外
Exception evaluating SpringEL expression: "bottle.product.name" (template: "reorder_request.html"
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'name' cannot be found on null
reorder_request.html
<tbody>
<tr th:if="${#lists.isEmpty(bottles)}">
<td colspan="2">Information not available</td>
</tr>
<tr th:each="bottle : ${bottles}">
<td colspan="4"><span th:text="${bottle.product.name}"> </span></td> <!-- trying to get the related product entity -->
</tr>
</tbody>
控制器
public class WGController {
@Validated
@PostMapping(value = "/wg/order/bottles/{wgId}")
public ResponseEntity<Void> reorderBottles(@Valid @RequestBody WGIO.ReorderBottles.ReorderRequest request, @PathVariable required = true) Long wgId) throws URISyntaxException {
Long wgId = wGService.sendReorderRequestEmail(request);
return ResponseEntity.created(new URI(wgId.toString())).build();
}
}
WG 服务
public class WGService {
public Long sendReorderRequestEmail(WGIO.ReorderBottles.ReorderRequest request) {
List<BottleReordering> bottles = request.getBottleReordering();
List<BottleReordering> requestedBottles = new ArrayList<>();
if(!CollectionUtils.isEmpty(bottles)) {
User user = userRepository.findUserById(request.getUserId());
bottles.forEach(rb -> {
BottleReordering bottle = new BottleReordering();
bottle.setProductId(rb.getProductId());
requestedBottles.add(bottle);
});
mailService.sendReorderEmail(user, requestedBottles);
}
}
邮件服务
public class MailService extends EmailService {
public void sendReorderEmail(User user, List<BottleReordering> bottles) {
Context context = createDefaultContext(user);
context.setVariable("bottles", bottles);
sendEmail(toEmail, fromEmail, fromName, createSubject("Reorder request"), context, "reorder_request.html")
}
}
产品实体
public class Product {
@Id
@Column(name = "id", updatable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "products_id_seq")
@SequenceGenerator(name="products_id_seq", sequenceName = "products_id_seq", initialValue = 100, allocationSize = 1)
private Long id;
@Column(name="name")
private String name;
@OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
private List<BottleReordering> bottleReordering;
}
BottleReordering 实体
public class BottleReordering implements Serializable {
@Column(name = "product_id")
private Long productId;
@JsonIgnore
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "product_id", nullable = false, updatable = false, insertable = false)
private Product product;
}
【问题讨论】:
标签: java spring spring-boot thymeleaf