spring data jpa,根本没法 lazy loading??

286 天前
 wganbleuthall
@Entity
public class ReckonerEntity {

    @OneToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @JoinColumn(name =  "from_acct")
    private AccountsEntity fromAcctEntity;
}


@Entity
public class AccountsEntity { }


public interface ReckonerRepository extends JpaRepository<ReckonerEntity, UUID>, JpaSpecificationExecutor<ReckonerEntity> { }



    @Bean
    @Transactional
    public CommandLineRunner runner() {
        return args -> {
            List<ReckonerEntity> reckoner = reckonerRepository.findAll();
            ReckonerEntity reckonerEntity = reckoner.get(0);
            AccountsEntity fromAcctEntity = reckonerEntity.getFromAcctEntity();
            log.info(fromAcctEntity.getName());
        };
    }
    

运行之后出错:org.hibernate.LazyInitializationException: could not initialize proxy [.....] - no Session 我尝试了 transactional 所有的 propagation 都不行,这明显是懒加载的错误

解决方案:

但是这所有的解决方案本质上不都是 eager loading 吗??

1239 次点击
所在节点    程序员
5 条回复
zhzy0077
285 天前
https://pastebin.com/t6cNBrU5

问题在于你在 lazy load 的时候没有把两个 select 放在一个 transaction 里
KevinBlandy
285 天前
我是 JPA 重度用户,但是从来不敢用这种 OOP 建模。实在是拿捏不住,太难维护了。

推荐一个优质的 spring/boot/data/security/cloud 的中文文档,无广告,无须登录,无须关注,在线读。

https://springdoc.cn/
qinxi
285 天前
开启 OpenSessionInView
wganbleuthall
285 天前
@qinxi 不推荐 https://www.baeldung.com/spring-open-session-in-view
问题找到了已经,很蠢
@Transactional
public CommandLineRunner runner() {
return args -> {
这种写法 导致 sql 不在同个事务里
Belmode
285 天前
@Transactional 的作用没整明白

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/961299

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX