JPA/Hibernate中一对一关联时不持有外键方的属性延迟加载为什么不生效?

问题

现在有2个实体:AuthorContact,关系是一对一,Contact表负责维护关联关系,如图:

实体定义如下:

  • Author
java 复制代码
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @OneToOne(fetch = FetchType.LAZY, mappedBy = "author")
    private Contact contact;
}
  • Contact
java 复制代码
public class Contact {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String mobile;
    private String email;
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn( name = "author_id",referencedColumnName = "id")
    private Author author;
}

现在有一个需求,要根据authorId查询author,但是不需要把author关联的contact也查出来,虽然我们这里配置了延迟加载contact,但是实际查询的时候,还是把contact查出来了,如下:

java 复制代码
@Transactional(readOnly = true)
public AuthorVO getById(Long id) {
   return authorRepository.findById(id)
           .map(author -> new AuthorVO(author.getId(), author.getName()))
           .orElse(null);
}

SQL日志:

java 复制代码
Hibernate: select a1_0.id,a1_0.name from author a1_0 where a1_0.id=?
Hibernate: select c1_0.id,c1_0.author_id,c1_0.email,c1_0.mobile from contact c1_0 where c1_0.author_id=?

点击查看完整内容https://mp.weixin.qq.com/s/NCc_N-8tXjnUvTah35Ov9g

相关推荐
Flittly15 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了16 小时前
Java 生成二维码解决方案
java·后端
人活一口气20 小时前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
NE_STOP1 天前
Vibe Coding -- 完整项目案例实操
java
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing1 天前
Google第三方授权登录
java·后端·程序员
明月光8181 天前
从一行 @Builder 说起:重新拾起 Java 的 Lombok、注解与 Builder 模式
java
考虑考虑1 天前
Mybatis实现批量插入
java·后端·mybatis
咖啡八杯1 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
青石路1 天前
记一次多JDK版本问题的排查,一坑套一坑,差点没爬上来
java