【问题标题】:Accessing a one to many relationship访问一对多关系
【发布时间】:2021-02-22 17:18:25
【问题描述】:

我正在使用Spring BootThymeLeaf 发送电子邮件。在电子邮件模板中,我需要为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}">&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;

}

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


    【解决方案1】:

    在您的控制器中,您“仅”设置产品 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);
     });
    

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多