java—访问一对多关系

niwlg2el  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(328)

我正在使用 Spring Boot 以及 ThymeLeaf 发送电子邮件。在电子邮件模板中,我需要检索相关的 product a的实体 bottle 然而,当我试图像这样检索它时,我总是得到一个错误 ${bottle.product.name} . 正确的方法是什么 name 从相关的 product 实体?
这是我得到的一个例外

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

重新订购申请.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}">&nbsp;</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;

}

重新排序实体

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;

}
lawou6xi

lawou6xi1#

在控制器中,“仅”设置产品id

bottles.forEach(rb -> {
      BottleReordering bottle = new BottleReordering();
      bottle.setProductId(rb.getProductId());
      requestedBottles.add(bottle);
 });

你应该装上产品,比如

bottles.forEach(rb -> {
      BottleReordering bottle = new BottleReordering();
      bottle.setProductId(rb.getProductId());
      bottle.setProcuct(productRepository.findById(rb.getProductId())) // <--- load product
      requestedBottles.add(bottle);
 });

相关问题