首页 > 解决方案 > 保存具有多个惰性关联的实体

问题描述

我有一个场景,我需要保存具有多个关联的实体,但如果不需要,我不想检索这些关联。

我将尝试举一个简单的例子:

实体:

public class Foo {
    private Long idFoo;
    private String defaultMessage;

    /* Getters and Setters Ommited */   
}

public class Bar {
    private Long idBar; 
    private String message;

    /*one-to-one lasy assoc*/   
    private Foo foo;

    /* Getters and Setters Ommited */
}

条形输入 DTO

Public class BarInputDTO {
    private String message;
    @NotNull
    private idFoo;

    /* Getters and Setters Ommited */
}

服务坚持吧

public void saveAsEntity(BarInputDTO dto) {
        Bar bar = new Bar();

        //Getting a reference do foo            
        bar.setFoo(fooRepository.getOne(dto.getIdFoo()));           

        if (dto.getMessage().equals("")) {
                /*
                * I just want to load the association if there is no message.
                * but get - LazyInitializationException: could not initialize proxy - no session
                */
                bar.setMessage(bar.getFoo().getDefaultMessage());
        } else {
                bar.setMessage(dto.getMessage);
        }

        barRepository.save(bar);
}

正如评论所说,如果没有消息,我只想加载关联。但是在这种情况下,我得到了一个 LazyInitializationException。如果有消息通知 Bar 被保存。

我知道 fooRepository.getOne 在调用时打开和关闭事务,然后当我调用 getDefaultMessage 时没有会话。我认为在方法中添加@Transaction 注释可以解决问题,但我错了。

当然,我可以直接从 if 子句中的 fooRepo 获取 Foo 对象,但我的实际情况要复杂一些,而且这将是一项非常重复的任务。

有什么我想念的东西让它工作吗?

谢!

标签: spring-bootjpalazy-loading

解决方案


推荐阅读